0
0
Selenium Pythontesting~15 mins

WebDriver setup (ChromeDriver, GeckoDriver) in Selenium Python - Build an Automation Script

Choose your learning style9 modes available
Setup WebDriver and open a browser
Preconditions (2)
Step 1: Import necessary Selenium WebDriver modules
Step 2: Create a WebDriver instance for Chrome or Firefox
Step 3: Open the browser and navigate to 'https://example.com'
Step 4: Verify the page title is 'Example Domain'
Step 5: Close the browser
✅ Expected Result: Browser opens, navigates to https://example.com, page title matches 'Example Domain', then browser closes
Automation Requirements - Selenium with Python
Assertions Needed:
Verify page title equals 'Example Domain'
Best Practices:
Use explicit waits if needed
Use try-finally to ensure browser closes
Use By selectors properly
Handle driver setup with options if needed
Automated Solution
Selenium Python
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.chrome.service import Service as ChromeService
from selenium.webdriver.firefox.service import Service as FirefoxService
import time

# Choose browser: 'chrome' or 'firefox'
browser = 'chrome'

try:
    if browser == 'chrome':
        service = ChromeService()  # Assumes chromedriver is in PATH
        driver = webdriver.Chrome(service=service)
    elif browser == 'firefox':
        service = FirefoxService()  # Assumes geckodriver is in PATH
        driver = webdriver.Firefox(service=service)
    else:
        raise ValueError('Unsupported browser')

    driver.get('https://example.com')

    # Assertion: check page title
    assert driver.title == 'Example Domain', f"Expected title 'Example Domain' but got '{driver.title}'"

finally:
    driver.quit()

This script sets up a WebDriver for Chrome or Firefox depending on the browser variable.

We import necessary modules from Selenium, including webdriver and By.

The Service classes are used to manage the driver executables assuming they are in the system PATH.

We open the browser and navigate to https://example.com.

We assert the page title matches the expected string 'Example Domain'. If it does not, the assertion fails and shows a message.

The try-finally block ensures the browser closes even if an error occurs.

This setup follows best practices by cleanly managing driver lifecycle and using clear assertions.

Common Mistakes - 4 Pitfalls
Not closing the browser after test
Hardcoding driver executable path without flexibility
Using deprecated Selenium APIs or missing imports
Not verifying page title or any assertion
Bonus Challenge

Now add data-driven testing to open both Chrome and Firefox browsers and verify the page title for each

Show Hint