Selenium – Scroll up to top of the webpage

Python Selenium – Scroll up to top of the page

To scroll up to top of the webpage using Selenium in Python, you can use the execute_script() method to run JavaScript code that performs the scrolling action.

The syntax of the execute_script() method with the JavaScript code is given below.

driver.execute_script("window.scrollTo(0, 0);")

This code scrolls the page to the position of (0, 0) which is the top left corner of the webpage.

Example

In the following program, we load the URL https://pythonexamples.org/#colophon, which loads the page and by default scrolls to the element with id=colophon, which is at the bottom of the page. Then using execute_script() method, we shall scroll up to the top.

Python Program

from selenium import webdriver
from selenium.webdriver.chrome.service import Service as ChromeService
from webdriver_manager.chrome import ChromeDriverManager
import time

# Setup chrome driver
driver = webdriver.Chrome(service=ChromeService(ChromeDriverManager().install()))

# Navigate to the url
driver.get('https://pythonexamples.org/#colophon')

# Wait for the page to load (optional)
time.sleep(2)

# Scroll to the top using JavaScript
driver.execute_script("window.scrollTo(0, 0);")

# Wait for a moment to let the page scroll (optional)
time.sleep(2)

# Close the WebDriver
driver.quit()

Output

Summary

In this Python Selenium tutorial, we have seen how to scroll up to the top of the page, with examples.

Related Tutorials

Quiz on Selenium

Q1. Which of the following is not a popular web driver used in Selenium Python?

Not answered

Q2. What is the method used to find web elements in Selenium Python?

Not answered

Q3. What is the method used to navigate back to the previous page in Selenium Python?

Not answered

Q4. Which of the following is not a commonly used assertion method in Selenium Python?

Not answered

Q5. What is the method used to clear the text from an input field in Selenium Python?

Not answered
Code copied to clipboard successfully 👍