Scroll down a webpage using JavaScript in Selenium
Preconditions (2)
✅ Expected Result: The page scrolls down by 500 pixels and the scroll position confirms the scroll
from selenium import webdriver from selenium.webdriver.common.by import By from selenium.webdriver.chrome.service import Service from selenium.webdriver.chrome.options import Options import time # Setup Chrome WebDriver options = Options() options.add_argument('--headless=new') # Run headless for testing service = Service() driver = webdriver.Chrome(service=service, options=options) try: # Navigate to the page with enough content to scroll driver.get('https://example.com/longpage') # Wait for page to load time.sleep(2) # Simple wait for demo; explicit waits preferred in real tests # Scroll down 500 pixels vertically using JavaScript driver.execute_script('window.scrollBy(0, 500);') # Get the current vertical scroll position scroll_position = driver.execute_script('return window.pageYOffset;') # Assert scroll position is at least 500 assert scroll_position >= 500, f"Scroll position {scroll_position} is less than 500" finally: driver.quit()
This script opens a Chrome browser in headless mode and navigates to a long page.
It waits briefly to ensure the page loads, then uses driver.execute_script() to run JavaScript that scrolls the window down by 500 pixels.
After scrolling, it retrieves the vertical scroll position with JavaScript and asserts it is at least 500 pixels, confirming the scroll happened.
Finally, it closes the browser.
This approach uses JavaScript scrolling because Selenium's native scroll methods are limited, and JavaScript gives precise control.
Now add data-driven testing to scroll by 100, 300, and 700 pixels and verify each scroll
driver.execute_script('window.scrollTo(0, document.body.scrollHeight)')element = driver.find_element(By.ID, 'footer')
driver.execute_script('scrollIntoView()', element)Pass the test and this pattern moves unknown