How to scroll to specific element in Selenium Python?

Python Selenium – Scroll to element

To scroll to a specific element in the webpage using Selenium in Python, you can use the execute_script() method to run JavaScript code that performs the scrolling action to the specified element.

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

driver.execute_script("arguments[0].scrollIntoView();", element)

This code scrolls down the page to the starting of the element.

Example

In the following program, we load the URL https://pythonexamples.org/tmp/selenium/index-29.html, and scroll to the element with id=”para3″.

Python Program

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

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

# Navigate to the url
driver.get('https://pythonexamples.org/tmp/selenium/index-29.html')

# Get the element
the_element = driver.find_element(By.ID, "para3")

time.sleep(2)

# Scroll to the element using JavaScript
driver.execute_script("arguments[0].scrollIntoView();", the_element)

time.sleep(3)

# Close the driver
driver.quit()

We have introduced some time delay before and after the scrolling action.

Summary

In this Python Selenium tutorial, we have seen how to scroll to a specific element in the web page, with examples.

Quiz on Selenium

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

Not answered

Q2. Which of the following is not a method to wait for a web element to load in Selenium Python?

Not answered

Q3. What is the method used to switch to a different frame in Selenium Python?

Not answered

Q4. What is the method used to select a value from a drop-down list 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 👍