How to Scroll to the Top or Bottom of a Web Page using the Selenium Module in Python



Python


In this article, we show how to scroll to the top or bottom of a web page using the selenium module in Python.

So the selenium module in Python is a very dynamic and useful module when working with web browsers such as Firefox or Chrome.

Using the selenium module, we can open up a browser, go to any URL we need to go to and scroll up or down the page.

We can scroll to the bottom or top of the page by first identifying the html element on the web page and then using the send_keys() function and specifying as a parameter, Keys.END, to scroll to the bottom of the page or the parameter, Keys.HOME, to scroll to the top of the page.

The code to scroll to the top or bottom of a web page is shown below.



The send_keys() function allows us to scroll up and down the page. Whether it scrolls up or down is controlled by the parameter specified within the function. Keys.END scrolls down the page. Keys.HOME scrolls up the page.

Below we give full code of us opening the Firefox web browser, going to the amazon home page, and scrolling down to the bottom of the page, and then scrolling up back to the top of the page.



So we import webdriver from the selenium module, which will allow us to connect to a browser, in this case, Firefox.

Next, we must import Keys from selenium.webdriver.common.keys

This allows us to work with all types of special Key characters that allow us to do special key functions, such as scrolling to the bottom or top of a web page. These also include special key functions such as emulating the 'TAB' key, F1-F12 keys, the Esc key, the Enter key, etc.

We connect to the Firefox web browser through the line, browser= webdriver.Firefox()

We go to the amazon home page using the get() function

A notable thing about scrolling to the top or bottom of a web page is that we do so by identifying the html tag element on the web page and using this as a reference. For every web page, the html tag is the first and last element of a web page. We use this to scroll to the bottom most HTML element with the parameter, Keys.END, and to the top most HTML element with the parameter, Keys.HOME

So when we run this program, we see that it opens up the amazon website and scrolls to the bottom of the page and then to the top of the page.

And this is how to scroll to the top or bottom of a web page using the Selenium module in Python.


Related Resources

How to Create a Zip File in Python

How to Extract All Files and Folders from a Zip File in Python

How to Read the Contents of a Zip File in Python



HTML Comment Box is loading comments...