0
0
Selenium Pythontesting~15 mins

JavaScript executor basics in Selenium Python - Build an Automation Script

Choose your learning style9 modes available
Use JavaScript executor to scroll and get page title
Preconditions (2)
Step 1: Open the browser and navigate to https://example.com
Step 2: Use JavaScript executor to scroll down 500 pixels vertically
Step 3: Use JavaScript executor to get the page title
Step 4: Verify the page title matches 'Example Domain'
✅ Expected Result: The page scrolls down 500 pixels and the page title is 'Example Domain'
Automation Requirements - Selenium with Python
Assertions Needed:
Verify the page title is exactly 'Example Domain'
Best Practices:
Use explicit waits to ensure page is loaded before executing JavaScript
Use driver.execute_script() for JavaScript execution
Avoid hardcoded waits like time.sleep()
Use clear and descriptive variable names
Automated Solution
Selenium Python
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.

Common Mistakes - 4 Pitfalls
Using time.sleep() instead of explicit waits
Not using driver.execute_script() for JavaScript execution
Not verifying the page title after getting it with JavaScript
Using vague or incorrect selectors for elements when not needed
Bonus Challenge

Now add data-driven testing to scroll different pixel values: 100, 300, and 700

Show Hint