Quick Learning guide: Python (Pytest) with Selenium Automation

Quick Learning guide: Python (Pytest) with Selenium Automation


1. Introduction to pytest and Selenium

What is pytest?

  • pytest is a popular Python testing framework, known for its simplicity and scalability.
  • It supports fixtures, parameterized testing, and has built-in plugins for advanced testing needs.

What is Selenium?

  • Selenium is a widely used tool for automating web browsers.
  • Supports various browsers (e.g., Chrome, Firefox) and programming languages.

Why pytest + Selenium?

  • Easy test execution with detailed reporting.
  • Reusable test setups with fixtures.
  • Parameterized testing for testing multiple data sets.


2. Environment Setup

Install Required Libraries

pip install selenium pytest pytest-html

pip install webdriver-manager        

Install WebDriver

Use webdriver-manager to simplify driver management.

Example for ChromeDriver:

from selenium import webdriver

from selenium.webdriver.chrome.service import Service

from webdriver_manager.chrome import ChromeDriverManager

driver = webdriver.Chrome(service=Service(ChromeDriverManager().install()))

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

driver.quit()


3. Pytest Basics

Writing a Basic Test

File: test_example.py

def test_example():

    assert 1 + 1 == 2

Run the test:

pytest test_example.py

Key pytest Features:

Assertions: Use Python’s assert statement.

  • Markers: Add metadata (e.g., @pytest.mark.smoke).
  • Fixtures: Reusable setup and teardown logic.


4. Selenium with pytest

Example Test Case: Open a Website

File: test_google.py

from selenium import webdriver
from selenium.webdriver.chrome.service import Service
from webdriver_manager.chrome import ChromeDriverManager
 
def test_open_google():

    driver = webdriver.Chrome(service=Service(ChromeDriverManager().install()))
    driver.get("https://www.google.com")
    assert "Google" in driver.title
    driver.quit()        

5. Pytest Fixtures

What are Fixtures?

Fixtures help manage setup and teardown logic for tests.

Example: Browser Fixture

File: conftest.py

import pytest
from selenium import webdriver
from selenium.webdriver.chrome.service import Service
from webdriver_manager.chrome import ChromeDriverManager

@pytest.fixture

def browser():

     driver = webdriver.Chrome(service=Service(ChromeDriverManager().install()))
     yield driver
     driver.quit()         

Use the fixture in your test:

 def test_open_google(browser):
     browser.get("https://www.google.com")
     assert "Google" in browser.title        

6. Locators in Selenium

  • ID: driver.find_element(By.ID, "element_id")
  • Name: driver.find_element(By.NAME, "element_name")
  • XPath: driver.find_element(By.XPATH, "//tag[@attribute='value']")
  • CSS Selector: driver.find_element(By.CSS_SELECTOR, "tag[attribute='value']")

Example

 from selenium.webdriver.common.by import By

def test_google_search(browser):

     browser.get("https://www.google.com")
     search_box = browser.find_element(By.NAME, "q")
     search_box.send_keys("pytest with Selenium")
     search_box.submit()
     assert "pytest" in browser.page_source        

7. Assertions in pytest

  • Basic Assertions: assert 1 == 1

assert "Google" in driver.title        

  • Custom Error Messages: assert "Bing" in driver.title, "Title did not contain Bing"


8. Parameterized Testing

Run tests with multiple sets of data.

Example

import pytest
@pytest.mark.parametrize("query", ["pytest", "Selenium", "Python"])
def test_search(browser, query):
    browser.get("https://www.google.com")
    search_box = browser.find_element(By.NAME, "q")
    search_box.send_keys(query)
    search_box.submit()
    assert query in browser.page_source        

9. Reports with pytest-html

Generate HTML reports for better insights.

Install pytest-html        
pip install pytest-html        

Run Tests with HTML Report

pytest --html=report.html        

10. Common Use Cases

Login Test

def test_login(browser):
    browser.get("https://example.com/login")
    browser.find_element(By.ID, "username").send_keys("test_user")
    browser.find_element(By.ID, "password").send_keys("password123")
    browser.find_element(By.ID, "login_button").click()
    assert "Welcome" in browser.page_source        

Form Submission

def test_form_submission(browser):
    browser.get("https://example.com/form")
    browser.find_element(By.NAME, "first_name").send_keys("John")
    browser.find_element(By.NAME, "last_name").send_keys("Doe")
    browser.find_element(By.NAME, "submit").click()
    assert "Thank you" in browser.page_source        

11. Handling Dynamic Waits

Implicit Waits

Sets a default wait time for all elements.

browser.implicitly_wait(10)  # Wait up to 10 seconds        

Explicit Waits

Waits for a specific condition to be met before proceeding.

from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait 
from selenium.webdriver.support import expected_conditions as EC


def test_explicit_wait(browser):
     browser.get("https://example.com")
     element = WebDriverWait(browser, 10).until(
         EC.presence_of_element_located((By.ID, "dynamic_element"))
     )

    assert element is not None        

Fluent Waits

Checks for a condition at regular intervals until a timeout occurs.

from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC

def test_fluent_wait(browser):
    wait = WebDriverWait(browser, timeout=10, poll_frequency=1)
    element = wait.until(EC.presence_of_element_located((By.ID,      "dynamic_element")))
    assert element.is_displayed()        

12. Handling Alerts

Simple Alerts

alert = browser.switch_to.alert        
assert alert.text == "This is a simple alert"        
alert.accept()         

Confirmation Alerts

alert = browser.switch_to.alert        
alert.dismiss()  # Click 'Cancel'        

Prompt Alerts

alert = browser.switch_to.alert        
alert.send_keys("Test Input")        
alert.accept()        

13. Types of Exceptions and Handling

Common Selenium Exceptions

  • NoSuchElementException: Element not found.
  • TimeoutException: Wait timeout exceeded.
  • StaleElementReferenceException: Element no longer attached to the DOM.
  • ElementNotInteractableException: Element not interactable.

Handling Exceptions

Use try-except blocks to handle exceptions gracefully.

from selenium.common.exceptions import NoSuchElementException
def test_exception_handling(browser):
    try:
        browser.get("https://example.com")
        browser.find_element(By.ID, "non_existent_element")
    except NoSuchElementException:
        print("Element not found")        

14. Parallel Execution in pytest

Install pytest-xdist

 pip install pytest-xdist        

Run Tests in Parallel

pytest -n 4  # Runs tests in 4 parallel threads        

Example

If you have multiple test files, they will run concurrently:

pytest tests/ -n auto  # Automatically detect the number of available CPU cores        

15. Multi-Tab Handling

Automating scenarios involving multiple browser tabs.

Example

from selenium.webdriver.common.by import By

def test_multi_tab_handling(browser):
    browser.get("https://example.com")
    browser.execute_script("window.open('https://google.com', '_blank');")
    # Get all window handles
    tabs = browser.window_handles 
    # Switch to the new tab
    browser.switch_to.window(tabs[1])
    assert "Google" in browser.title
     # Switch back        



16. Best Practices

  1. Use fixtures for setup and teardown.
  2. Avoid hardcoding locators or test data.
  3. Group tests with markers (e.g., @pytest.mark.smoke).
  4. Use pytest-html for clear reporting.
  5. Handle browser waits effectively (use WebDriverWait for dynamic elements).
  6. Leverage parallel execution for faster test runs.

"Fantastic guide! Selenium paired with Python and Pytest is a powerful combination for test automation.  Santhanakumar S

Like
Reply

To view or add a comment, sign in

More articles by Santhanakumar S

  • Quick Guide to Playwright with Detailed Study

    1. Introduction Playwright is an open-source, cross-browser automation testing tool developed by Microsoft.

  • Advanced Feature n Selenium4

    Selenium 4 brought several exciting features and improvements over Selenium 3 1. W3C WebDriver Standardization •…

Others also viewed

Explore content categories