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 /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('/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.