Is it possible to scroll down in a webpage using Selenium Webdriver programmed on Python?

SeleniumAutomation TestingTesting Tools

Yes it is possible to scroll down in a webpage using Selenium webdriver in Python by using the JavaScript Executor. Selenium can execute JavaScript commands with the help of execute_script method.

The JavaScript command to be used is passed as a parameter to this method. Also, it must be noted that scrolling actions cannot be performed directly with any methods in Selenium.

To scroll down in a page to the end, we have to pass the command window.scrollTo as a parameter to the execute_script method. Also, the values 0 and document.body.scrollHeight are passed as parameters to the window.scrollTo command.

Syntax

driver.execute_script("window.scrollTo(0, document.body.scrollHeight);")

Let us scroll to the page end and obtain the text CONTACT US −

Example

from selenium import webdriver
#set chromodriver.exe path
driver = webdriver.Chrome(executable_path="C:\\chromedriver.exe")
driver.implicitly_wait(0.5)
#launch URL
driver.get("https://www.tutorialspoint.com/index.htm")
#scroll to page end with JavaScript Executor
driver.execute_script("window.scrollTo(0, document.body.scrollHeight);")
#identify element at page end
m = driver.find_element_by_xpath("//h3[text()='Contact Us']")
#get element text
s = m.text
print("Text is: ")
print(s)
#close browser
driver.quit()

Output

raja
Published on 06-Apr-2021 11:47:16
Advertisements