Use JavaScript executor to scroll and get page title
Preconditions (2)
✅ Expected Result: The page scrolls down 500 pixels and the page title is 'Example Domain'
from selenium import webdriver from selenium.webdriver.chrome.service import Service from selenium.webdriver.common.by import By from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.support import expected_conditions as EC # Setup Chrome WebDriver service = Service() driver = webdriver.Chrome(service=service) try: driver.get('https://example.com') # Wait until the page title contains 'Example Domain' WebDriverWait(driver, 10).until(EC.title_contains('Example Domain')) # Scroll down 500 pixels vertically using JavaScript executor driver.execute_script('window.scrollBy(0, 500);') # Get the page title using JavaScript executor page_title = driver.execute_script('return document.title;') # Assert the page title is exactly 'Example Domain' assert page_title == 'Example Domain', f"Expected title 'Example Domain' but got '{page_title}'" finally: driver.quit()
This script opens the browser and navigates to https://example.com.
It waits explicitly until the page title contains 'Example Domain' to ensure the page is fully loaded.
Then it uses driver.execute_script() to scroll down 500 pixels vertically.
Next, it uses JavaScript executor again to get the page title directly from the browser.
Finally, it asserts that the page title exactly matches 'Example Domain'.
The try-finally block ensures the browser closes even if the test fails.
Now add data-driven testing to scroll different pixel values: 100, 300, and 700
execute_script in Selenium with Python?execute_scriptexecute_script specifically runs JS code.execute_script in Python?title = driver.execute_script('return document.title')
print(title)driver.execute_script(return document.body.style.backgroundColor = 'red')
window.scrollBy(x, y) scrolls by x and y pixels relative to current position.Pass the test and this pattern moves unknown