Testing & Code Quality

Selenium Setup & Deployment Guide

Browser automation with WebDriver – write tests in Python with pytest, use explicit waits, run headless and scale with Selenium Grid in Docker.

Updated Official documentation ↗

1. Introduction & use cases

Selenium automates real web browsers through the W3C WebDriver standard. It supports Chrome, Firefox, Edge and Safari and has official bindings for Java, Python, C#, JavaScript and Ruby, which is why it is widely used in QA teams and enterprise test suites.

Since Selenium 4.6, Selenium Manager downloads the right browser driver automatically. Selenium Grid runs tests in parallel on many browsers and machines – easily in Docker.

Where it is used

  • Regression and end-to-end UI testing
  • Cross-browser testing on many browser/OS combinations
  • Automating repetitive browser tasks (with permission)
  • Large QA suites in Java or Python

2. Prerequisites

You needVersion / notes
Python 3Or Java/C#/JavaScript – this guide uses Python
A browserChrome, Firefox or Edge installed locally
Docker (optional)For Selenium Grid
pytestTest runner

3. Local setup

  1. 1Create a venv and install Selenium

    pytest runs the tests.

    BASH
    python3 -m venv .venv
    source .venv/bin/activate      # Windows: .venv\Scripts\activate
    pip install selenium pytest
  2. 2Check that a browser starts

    Selenium Manager finds/downloads the matching driver automatically.

    BASH
    python -c "from selenium import webdriver; d = webdriver.Chrome(); d.get('https://www.selenium.dev'); print(d.title); d.quit()"

4. Create & run a project

  1. 1Write a test with explicit waits

    Wait for conditions instead of sleeping; always quit the browser.

    tests/test_search.py
    import pytest
    from selenium import webdriver
    from selenium.webdriver.common.by import By
    from selenium.webdriver.support.ui import WebDriverWait
    from selenium.webdriver.support import expected_conditions as EC
    
    @pytest.fixture
    def driver():
        options = webdriver.ChromeOptions()
        options.add_argument("--headless=new")
        options.add_argument("--window-size=1280,900")
        d = webdriver.Chrome(options=options)
        yield d
        d.quit()
    
    def test_search(driver):
        driver.get("https://www.selenium.dev")
        wait = WebDriverWait(driver, 10)
        wait.until(EC.element_to_be_clickable((By.CSS_SELECTOR, "button.DocSearch"))).click()
        box = wait.until(EC.visibility_of_element_located((By.ID, "docsearch-input")))
        box.send_keys("WebDriver")
        assert "Selenium" in driver.title
  2. 2Run it

    -v shows each test name.

    BASH
    pytest -v
  3. 3Organise with page objects

    Keep locators and actions in classes so tests stay readable and changes are made in one place.

    pages/login_page.py
    class LoginPage:
        def __init__(self, driver):
            self.driver = driver
        def open(self, base):
            self.driver.get(f"{base}/login")
            return self
        def login(self, email, password):
            self.driver.find_element(By.NAME, "email").send_keys(email)
            self.driver.find_element(By.NAME, "password").send_keys(password)
            self.driver.find_element(By.CSS_SELECTOR, "button[type=submit]").click()
  4. 4Run a Selenium Grid in Docker

    A standalone Chrome node listens on port 4444 (dashboard at http://localhost:4444). Point tests to it with webdriver.Remote.

    BASH
    docker run -d -p 4444:4444 --shm-size="2g" selenium/standalone-chrome:latest
    
    # in the fixture
    d = webdriver.Remote(command_executor="http://localhost:4444", options=webdriver.ChromeOptions())

✅ When it works you should see output like Figure 1.

5. Development configuration

Environment variables

Pass the target URL, browser and Grid address as environment variables so the same suite runs locally, in CI and against staging.

.env
BASE_URL=http://localhost:5173
BROWSER=chrome
SELENIUM_REMOTE_URL=http://localhost:4444   # empty = local browser

Key dependencies

Package / toolUsed for
seleniumWebDriver bindings (Python)
Selenium ManagerAutomatic driver management (built in)
pytest (+ pytest-xdist)Runner (+ parallel runs)
Selenium GridRemote/parallel browsers (Docker images)
pytest-html / allureReports

Folder structure

project structure
e2e/
├── pages/             # page objects
│   └── login_page.py
├── tests/
│   ├── conftest.py    # driver fixture
│   └── test_login.py
├── requirements.txt
└── pytest.ini

Essential commands

CommandWhat it does
pytest -vRun tests
pytest -n 4Parallel (pytest-xdist)
pytest -k loginRun matching tests
pytest --html=report.htmlHTML report (pytest-html)
docker run … selenium/standalone-chromeLocal Grid node

6. Production deployment

Test frameworks are not deployed to a production server – in production they act as a quality gate: they run automatically in CI on every push and pull request, publish reports, and block the deployment when a test fails. Selenium suites often run against a staging environment after deployment, using a Grid for parallel browsers.

Server & hosting requirements

RequirementRecommendation
CI runnerLinux runner with Chrome, or a Selenium Grid service/container
Headless mode--headless=new for Chrome
TargetLocal app started in CI, or a staging URL
ReportsHTML/JUnit reports + screenshots on failure as artifacts

Deployment steps

  1. 1Run in GitHub Actions with a Grid service container

    The workflow starts Selenium in a service container and runs pytest against it.

    .github/workflows/e2e.yml
    name: e2e
    on: [push, pull_request]
    jobs:
      selenium:
        runs-on: ubuntu-latest
        services:
          selenium:
            image: selenium/standalone-chrome:latest
            ports: ['4444:4444']
            options: --shm-size=2g
        steps:
          - uses: actions/checkout@v4
          - uses: actions/setup-python@v5
            with: { python-version: '3.12' }
          - run: pip install -r requirements.txt
          - run: pytest -v --junitxml=reports/junit.xml
            env:
              SELENIUM_REMOTE_URL: http://localhost:4444
              BASE_URL: https://staging.example.com
  2. 2Save screenshots on failure

    Add a pytest hook that stores a screenshot when a test fails, then upload reports/ as an artifact.

    PYTHON
    # conftest.py
    import pytest
    
    @pytest.hookimpl(hookwrapper=True)
    def pytest_runtest_makereport(item, call):
        outcome = yield
        rep = outcome.get_result()
        if rep.when == "call" and rep.failed and "driver" in item.fixturenames:
            item.funcargs["driver"].save_screenshot(f"reports/{item.name}.png")
  3. 3Gate releases

    Require the e2e job (or a smoke subset) to pass before promoting a build to production.

🗺 The whole path from your code to the live site is drawn in the deployment diagram.

7. Images & screenshots

Illustrations drawn for this guide from the commands above. Product dashboards change often, so for screens such as cloud consoles follow the step text and the official documentation.

terminal$ pytest -v============================= test session starts =============================collected 2 itemstests/test_search.py::test_search PASSED [ 50%]tests/test_login.py::test_login PASSED [100%]============================== 2 passed in 6.84s ==============================
Figure 1: terminal output of the sample Selenium project (section 4).
1pytest + pageobjects2Headless locally3CI + Gridcontainer4Tests vs staging5Reports + gate
Figure 2: production deployment flow (section 6).
e2e/├── pages/ # page objects│ └── login_page.py├── tests/│ ├── conftest.py # driver fixture│ └── test_login.py├── requirements.txt└── pytest.ini
Figure 3: project folder structure (section 5).

8. Common errors & solutions

SessionNotCreatedException: This version of ChromeDriver only supports Chrome version X

Driver and browser versions differ. Remove old drivers from PATH and let Selenium Manager (Selenium 4.6+) choose the matching driver.

NoSuchElementException

The element is not there yet or the locator is wrong. Use WebDriverWait with expected conditions and check the locator in DevTools.

StaleElementReferenceException

The page re-rendered. Find the element again after navigation/updates instead of reusing old references.

ElementClickInterceptedException

Another element (cookie banner, overlay) covers it. Close the overlay or wait for element_to_be_clickable.

Chrome crashes in Docker/CI

Increase shared memory (--shm-size=2g) and run headless.

Best practices

  • Use explicit waits; never time.sleep for synchronisation.
  • Prefer stable locators (ids, names, data-test attributes).
  • Use page objects to keep tests maintainable.
  • Always quit() the driver (fixtures do this for you).
  • Consider Playwright for new JavaScript projects needing auto-waiting.