Scrolling a Web Page - (Selenium WebDriver)
Description
In Selenium WebDriver, to scroll down or up a web page, we can use the execute_script()
method to execute a JavaScript code. We can use this method to scroll the web page to a certain point or to the bottom or top of the web page.
Syntax
driver.execute_script("window.scrollTo(0, document.body.scrollHeight)")
Example
from selenium import webdriver
driver = webdriver.Chrome()
driver.maximize_window()
driver.get("https://www.example.com")
# Scroll to bottom of the page
driver.execute_script("window.scrollTo(0, document.body.scrollHeight)")
# Scroll to top of the page
driver.execute_script("window.scrollTo(0, -document.body.scrollHeight)")
Output
The above-given code will scroll the web page to the bottom or top of the page.
Explanation
window.scrollTo()
method is used to scroll the web page.0
is used to scroll horizontally to the extreme left of the web page.document.body.scrollHeight
returns the height of the web page.-document.body.scrollHeight
is used to scroll to the top of the web page.
Use
This technique is mostly used to automate scrolling to the bottom of the web page to load more data or when we need to perform any action on a web page which will only appear after scrolling down.
Important Points
- We can use
window.scrollBy()
method to scroll the web page by a specified amount of pixels in a horizontal and vertical direction. - Selenium WebDriver also provides
ActionChains
class to perform scrolling actions.
Summary
- In Selenium WebDriver, we can use
execute_script()
method to scroll the web page. - We can scroll to the bottom or top of the web page using this technique.