0
0
Selenium Pythontesting~15 mins

Docker-based Grid in Selenium Python - Build an Automation Script

Choose your learning style9 modes available
Run Selenium test on Docker-based Selenium Grid
Preconditions (3)
Step 1: Write a Selenium test script that connects to the Selenium Grid hub URL
Step 2: Configure the test to use Chrome browser capabilities
Step 3: Navigate to 'https://example.com' in the test
Step 4: Verify the page title is 'Example Domain'
Step 5: Close the browser session
✅ Expected Result: The test connects to the Docker Selenium Grid, runs on the Chrome node, navigates to the page, verifies the title, and finishes without errors.
Automation Requirements - Selenium with Python
Assertions Needed:
Assert page title equals 'Example Domain'
Best Practices:
Use Remote WebDriver to connect to Selenium Grid hub
Use explicit waits if needed
Use proper capabilities for browser selection
Close the driver session after test
Automated Solution
Selenium Python
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.chrome.options import Options
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC

# Selenium Grid hub URL (adjust if needed)
hub_url = 'http://localhost:4444/wd/hub'

# Set Chrome options
chrome_options = Options()

# Create Remote WebDriver instance
with webdriver.Remote(
    command_executor=hub_url,
    options=chrome_options
) as driver:
    # Navigate to the test page
    driver.get('https://example.com')

    # Wait until title is present and verify it
    WebDriverWait(driver, 10).until(EC.title_is('Example Domain'))
    assert driver.title == 'Example Domain', f"Expected title 'Example Domain' but got '{driver.title}'"

    # Driver will quit automatically due to 'with' context

The code uses Selenium's Remote WebDriver to connect to the Selenium Grid hub running in Docker at http://localhost:4444/wd/hub. We set Chrome options to specify the browser type.

The test navigates to https://example.com and waits explicitly until the page title is exactly 'Example Domain'. This ensures the page loaded correctly before asserting.

The assertion checks the page title matches the expected value. Using a with block ensures the browser session closes automatically after the test, which is a good practice to avoid leftover sessions.

Common Mistakes - 4 Pitfalls
Using local WebDriver instead of Remote WebDriver
Hardcoding browser capabilities incorrectly or missing them
Not waiting for page elements or title before asserting
Not closing the WebDriver session after test
Bonus Challenge

Now add data-driven testing to run the same test on three different URLs with their expected titles.

Show Hint