0
0
Selenium Pythontesting~10 mins

JavaScript executor basics in Selenium Python - Test Execution Trace

Choose your learning style9 modes available
Test Overview

This test uses Selenium with Python to open a webpage and run JavaScript code inside the browser. It verifies that the JavaScript executor correctly returns the page title.

Test Code - Selenium
Selenium Python
from selenium import webdriver
from selenium.webdriver.chrome.service import Service
from selenium.webdriver.common.by import By
from selenium.webdriver.chrome.options import Options

# Setup Chrome driver
options = Options()
options.add_argument('--headless')
service = Service()
driver = webdriver.Chrome(service=service, options=options)

try:
    # Open example page
    driver.get('https://example.com')

    # Execute JavaScript to get document title
    title = driver.execute_script('return document.title;')

    # Assert the title is 'Example Domain'
    assert title == 'Example Domain', f"Title was '{title}' instead of 'Example Domain'"
finally:
    driver.quit()
Execution Trace - 5 Steps
StepActionSystem StateAssertionResult
1Test starts and Chrome browser is launched in headless modeChrome browser is open but not visible, ready to navigate-PASS
2Browser navigates to 'https://example.com'Page loads with title 'Example Domain' visible in DOM-PASS
3Execute JavaScript 'return document.title;' using Selenium's execute_script methodJavaScript runs inside browser context and returns the page title stringCheck that returned title equals 'Example Domain'PASS
4Assert that the returned title is exactly 'Example Domain'Title string matches expected valueassert title == 'Example Domain'PASS
5Close the browser and end the testBrowser closed, resources released-PASS
Failure Scenario
Failing Condition: The JavaScript executor returns a title different from 'Example Domain' or fails to execute
Execution Trace Quiz - 3 Questions
Test your understanding
What does the JavaScript executor return in this test?
AThe URL of the page
BThe page title string
CThe page HTML source
DAn error message
Key Result
Using JavaScript executor allows running custom scripts inside the browser, which is useful for accessing properties or performing actions not directly supported by Selenium commands.