0
0
Selenium Pythontesting~8 mins

Headless browser execution in Selenium Python - Framework Patterns

Choose your learning style9 modes available
Framework Mode - Headless browser execution
Folder Structure
selenium_project/
├── tests/
│   ├── test_login.py
│   └── test_search.py
├── pages/
│   ├── base_page.py
│   ├── login_page.py
│   └── search_page.py
├── utils/
│   ├── browser_factory.py
│   └── config_reader.py
├── config/
│   ├── config.yaml
│   └── credentials.yaml
├── reports/
│   └── test_report.html
├── conftest.py
└── requirements.txt
Test Framework Layers
  • Driver Layer: utils/browser_factory.py creates WebDriver instances with headless options.
  • Page Objects: pages/ contains classes representing web pages with element locators and actions.
  • Tests: tests/ holds test scripts using pytest that call page objects.
  • Utilities: Helpers like config readers and browser setup in utils/.
  • Configuration: config/ stores environment settings, browser options, and credentials.
Configuration Patterns

Use config/config.yaml to define environments and browser settings, including headless mode.

# config/config.yaml
browser: chrome
headless: true
base_url: "https://example.com"

In utils/browser_factory.py, read config and set browser options accordingly:

from selenium import webdriver
from selenium.webdriver.chrome.options import Options
import yaml

def create_driver():
    with open('config/config.yaml') as f:
        config = yaml.safe_load(f)
    options = Options()
    if config.get('headless', False):
        options.add_argument('--headless=new')
    driver = webdriver.Chrome(options=options)
    return driver
Test Reporting and CI/CD Integration
  • Use pytest with plugins like pytest-html to generate HTML reports saved in reports/.
  • Configure CI pipelines (GitHub Actions, Jenkins) to run tests in headless mode for faster execution without UI.
  • Reports are archived and emailed or uploaded to dashboards for team visibility.
Best Practices
  1. Use explicit waits: Avoid flaky tests by waiting for elements instead of fixed sleeps.
  2. Centralize browser setup: Manage headless options in one place (browser_factory.py) for easy changes.
  3. Keep tests independent: Each test should create and close its own driver instance.
  4. Use config files: Control headless mode and environment settings without code changes.
  5. Run headless in CI: Headless mode speeds up tests and avoids UI dependencies in automated pipelines.
Self Check

Where in this folder structure would you add a new browser option to run Firefox in headless mode?

Key Result
Use a centralized browser factory to configure headless browser options for fast, UI-free test execution.