0
0
Selenium Pythontesting~15 mins

First Selenium script in Selenium Python - Build an Automation Script

Choose your learning style9 modes available
Verify Google Search Page Title
Preconditions (2)
Step 1: Open Chrome browser
Step 2: Navigate to 'https://www.google.com'
Step 3: Wait for the page to load completely
Step 4: Check the page title
✅ Expected Result: The page title should be 'Google'
Automation Requirements - Selenium with Python
Assertions Needed:
Verify the page title is exactly 'Google'
Best Practices:
Use explicit waits to wait for page load
Use By.ID or By.NAME locators if needed
Close the browser after test
Handle exceptions gracefully
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
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.

Common Mistakes - 3 Pitfalls
Using time.sleep() instead of explicit waits
Not closing the browser after the test
Using incorrect locator strategies or hardcoded XPath for simple tasks
Bonus Challenge

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'.

Show Hint