How can I scroll a web page using selenium webdriver in python?


Sometimes we need to perform action on an element which is not present in the viewable area of the page. We need to scroll down to the page in order to reach that element.

Selenium cannot perform scrolling action directly. This can be achieved with the help of Javascript Executor and Actions class in Selenium. DOM can work on all elements on the web page with the help of Javascript.

Selenium can execute commands in Javascript with the help of the execute_script() method. For the Javascript solution, we have to pass true value to the method scrollIntoView() to identify the object below our current location on the page. We can execute mouse movement with the help of the Actions class in Selenium.

Example

Code Implementation with Javascript Executor.

import time
from selenium import webdriver
driver = webdriver.Chrome (executable_path="C:\chromedriver.exe")
driver.get("https://www.tutorialspoint.com/index.htm")
# identify element
l= driver.find_element_by_xpath("//*[text()='About Us']")
# Javascript Executor
driver.execute_script("arguments[0].scrollIntoView(true);", l)
time.sleep(0.4)
driver.close

While working with Actions class to scroll to view, we have to use the moveToElement() method. This method shall perform mouse movement till the middle of the element.

Example

Code Implementation with Actions.

from selenium.webdriver import ActionChains
from selenium import webdriver
driver = webdriver.Chrome (executable_path="C:\chromedriver.exe")
driver.get("https://www.tutorialspoint.com/index.htm")
# identify element
I=driver.find_element_by_xpath("//*[text()='About Us']")
# action object creation to scroll
a = ActionChains(driver)
a.move_to_element(l).perform()

Output


Updated on: 16-Feb-2021

2K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements