Run Selenium test on Docker-based Selenium Grid
Preconditions (3)
✅ 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.
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.
Now add data-driven testing to run the same test on three different URLs with their expected titles.
http://localhost:4444/wd/hub for Chrome browser?print(driver.title) output if the page at https://example.com has title "Example Domain"?
from selenium import webdriver
driver = webdriver.Remote(
command_executor='http://localhost:4444/wd/hub',
options=webdriver.FirefoxOptions()
)
driver.get('https://example.com')
print(driver.title)
driver.quit()from selenium import webdriver
driver = webdriver.Remote(
command_executor='http://localhost:5555/wd/hub',
options=webdriver.ChromeOptions()
)
driver.get('https://example.com')Pass the test and this pattern moves unknown