0
0
Selenium Pythontesting~15 mins

pytest with Selenium setup in Selenium Python - Build an Automation Script

Choose your learning style9 modes available
Verify Google Search Page Title
Preconditions (4)
Step 1: Open Chrome browser
Step 2: Navigate to https://www.google.com
Step 3: Verify the page title is 'Google'
Step 4: Close the browser
✅ Expected Result: The browser opens Google homepage and the page title is exactly 'Google'. The browser closes after verification.
Automation Requirements - pytest with Selenium WebDriver
Assertions Needed:
Assert that the page title equals 'Google'
Best Practices:
Use pytest fixtures for setup and teardown of WebDriver
Use explicit waits if needed (not required here as page loads quickly)
Use clear and maintainable locators (here no locators needed as only title is checked)
Close the browser properly after test
Automated Solution
Selenium Python
import pytest
from selenium import webdriver
from selenium.webdriver.chrome.service import Service
from selenium.webdriver.chrome.options import Options

@pytest.fixture

def driver():
    options = Options()
    options.add_argument('--headless=new')  # Run in headless mode for faster tests
    service = Service()  # Assumes chromedriver is in PATH
    driver = webdriver.Chrome(service=service, options=options)
    yield driver
    driver.quit()


def test_google_title(driver):
    driver.get('https://www.google.com')
    assert driver.title == 'Google', f"Expected title 'Google' but got '{driver.title}'"

This test uses pytest and selenium to automate opening Google homepage and checking its title.

The driver fixture sets up the Chrome WebDriver in headless mode for speed and isolation. It yields the driver to the test and ensures the browser closes after the test finishes.

The test function test_google_title navigates to Google and asserts the page title is exactly 'Google'. If the title is different, the assertion message will show the actual title.

This setup follows best practices by using fixtures for setup/teardown and clear assertions.

Common Mistakes - 4 Pitfalls
Not closing the browser after the test
Hardcoding WebDriver path inside the test
Not using headless mode for simple tests
Using implicit waits or sleeps unnecessarily
Bonus Challenge

Now add data-driven testing to verify titles of three different websites: Google, Bing, and DuckDuckGo.

Show Hint