First Selenium script in Selenium Python - Build an Automation Script
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 from selenium.common.exceptions import TimeoutException # Setup ChromeDriver service service = Service() # Create a new Chrome browser instance with webdriver.Chrome(service=service) as driver: try: # Navigate to Google homepage driver.get('https://www.google.com') # Wait up to 10 seconds for the title to be 'Google' WebDriverWait(driver, 10).until(EC.title_is('Google')) # Assert the page title assert driver.title == 'Google', f"Expected title 'Google' but got '{driver.title}'" print('Test Passed: Page title is Google') except TimeoutException: print('Test Failed: Page title did not become Google in time') except AssertionError as e: print(f'Test Failed: {e}')
This script uses Selenium WebDriver with Python to open the Chrome browser and navigate to the Google homepage.
We use WebDriverWait with expected_conditions.title_is to wait explicitly until the page title becomes exactly 'Google'. This avoids timing issues where the page might not be fully loaded yet.
The assertion checks that the title is exactly 'Google'. If it is, the test prints a success message; otherwise, it prints a failure message.
The with statement ensures the browser closes automatically after the test finishes, even if an error occurs.
This approach follows best practices by using explicit waits, proper assertions, and clean browser management.
Now add data-driven testing to open Google and verify the title for three different URLs: 'https://www.google.com', 'https://www.google.co.uk', and 'https://www.google.ca'.