To scroll up using Selenium in Python, you can use the Selenium webdriver execute_script() function which executes JavaScript code in the browser.
from selenium import webdriver
driver = webdriver.Chrome()
driver.get("https://daztech.com/")
#Scroll to Top of Webpage
driver.execute_script("window.scrollTo(0,0)")
The Selenium Python module gives you the tools you need to be able to automate many tasks when working with web browser.
When working with web browsers, it’s possible you may want to scroll up to the top of a webpage or scroll up to a particular pixel height.
To scroll up using Selenium in your Python code, you can use the Selenium webdriver execute_script() function. execute_script() is a versatile function and allows you to execute JavaScript code in the browser.
With JavaScript, we can easily scroll up in a browser.
How to Scroll Up to Top of Webpage Using Selenium
To scroll up to the top of a webpage using Selenium, you can use the execute_script() function to execute the JavaScript function window.scrollTo() and pass ‘0’ for the second parameter.
Below shows you a simple example of how you can use Selenium to scroll up to the top of a webpage.
from selenium import webdriver
driver = webdriver.Chrome()
driver.get("https://daztech.com/")
#Scroll to Top of Webpage
driver.execute_script("window.scrollTo(0,0)")
How to Scroll Up to Specific Height Using Selenium
If you want to scroll up to a specific pixel height, then you can change the second parameter of the window.scrollTo() function.
For example, if you want to scroll up to pixel 100, then pass ‘100’ to window.scrollTo().
Below shows you how to use Selenium to scroll up to a specific height in your Python code.
from selenium import webdriver
driver = webdriver.Chrome()
driver.get("https://daztech.com/")
#Scroll to Pixel Height 100
driver.execute_script("window.scrollTo(100))
Hopefully this article has been useful for you to learn how to scroll up using Selenium in Python.