0
0
Selenium Pythontesting~5 mins

Scrolling with JavaScript in Selenium Python

Choose your learning style9 modes available
Introduction

Sometimes, web pages are long and you need to move down or up to see elements. Scrolling with JavaScript helps you do this in tests.

When an element is not visible on the screen and you want to interact with it.
When you want to test lazy loading or infinite scrolling features.
When automatic scrolling is needed before clicking or reading an element.
When you want to scroll to the bottom or top of a page during a test.
When normal Selenium scroll actions don't work as expected.
Syntax
Selenium Python
driver.execute_script("window.scrollTo(x, y)")

x and y are pixel values for horizontal and vertical scroll positions.

You can also scroll to an element using driver.execute_script("arguments[0].scrollIntoView();", element).

Examples
Scrolls down 500 pixels vertically from the top of the page.
Selenium Python
driver.execute_script("window.scrollTo(0, 500)")
Scrolls to the very bottom of the page.
Selenium Python
driver.execute_script("window.scrollTo(0, document.body.scrollHeight)")
Scrolls the page until the element with ID 'footer' is visible.
Selenium Python
element = driver.find_element(By.ID, "footer")
driver.execute_script("arguments[0].scrollIntoView();", element)
Sample Program

This script opens a long webpage, scrolls down by pixels, then scrolls to the bottom, and finally scrolls to the footer element. It prints messages before each scroll to show progress.

Selenium Python
from selenium import webdriver
from selenium.webdriver.common.by import By
import time

# Setup driver (make sure chromedriver is in PATH)
driver = webdriver.Chrome()

# Open a long page
url = "https://www.example.com/longpage"
driver.get(url)

# Scroll down 600 pixels
print("Scrolling down 600 pixels...")
driver.execute_script("window.scrollTo(0, 600)")
time.sleep(2)  # wait to see the scroll effect

# Scroll to bottom
print("Scrolling to bottom...")
driver.execute_script("window.scrollTo(0, document.body.scrollHeight)")
time.sleep(2)

# Scroll to an element
footer = driver.find_element(By.TAG_NAME, "footer")
print("Scrolling to footer element...")
driver.execute_script("arguments[0].scrollIntoView();", footer)
time.sleep(2)

# Close driver
driver.quit()
OutputSuccess
Important Notes

Use time.sleep() to pause and see the scroll effect during testing.

Scrolling with JavaScript works even if Selenium's normal scroll actions fail.

Always close the browser with driver.quit() to free resources.

Summary

Scrolling helps reach elements not visible on screen.

Use execute_script with JavaScript commands to scroll.

You can scroll by pixels or directly to elements.