Selenium × Python Setup Guide [5 Minutes] | pytest + webdriver-manager, No More Version Errors

test-automation

This is a complete guide to setting up Selenium × Python — from scratch to passing tests — written so even beginners can get it done in 5 minutes.

👉 Copy the code in this article and your tests will be running in 5 minutes.

“ChromeDriver version mismatch.” “Stuck on environment setup.” — this guide solves both.

This article walks through a production-ready setup using Selenium, webdriver-manager, and pytest — the fastest path to running tests without errors.

👉 vs Playwright: Selenium operates browsers via WebDriver and is the industry standard with far more job postings and client projects than Playwright.

💡 What you’ll be able to do after this article
Set up a Selenium × Python × pytest environment and run a passing test that opens a real browser

💡 What makes this article different

Most guides tell you to manually download ChromeDriver. This article uses webdriver-manager to fully automate that process. That means no version mismatch errors — ever.

The two most common Selenium setup failures are “ChromeDriver version doesn’t match” and “PATH not configured.” This guide uses webdriver-manager to automate version management entirely — so you won’t hit either of those walls.

📌 Who This Article Is For

  • Anyone setting up Selenium × Python for the first time
  • Those who’ve been burned by ChromeDriver version mismatch before
  • Engineers who want to combine Selenium with pytest for automated testing
  • QA engineers building a Selenium portfolio for Upwork clients

✅ What You’ll Learn

  • How to install Python virtual environment, Selenium, and webdriver-manager
  • How to automate ChromeDriver version management with webdriver-manager
  • How to write and run a basic test combining pytest and Selenium

👤 About the Author

Written by Yoshi, a QA and test automation engineer with 15+ years of hands-on experience. This setup — with webdriver-manager as the standard — comes directly from production workflows where manual ChromeDriver management caused too many avoidable failures. Code is publicly available on GitHub: github.com/YOSHITSUGU728/automated-testing-portfolio

Selenium × Python Setup: Full Overview

Here’s the complete flow before diving in.

🗺️ Setup Flow

1Verify Python installationCheck with python –version
2Create virtual environment (venv)Isolate dependencies per project
3Install Selenium, webdriver-manager, pytestOne pip install command
4Set up project structurepytest.ini + tests/ folder
5Configure WebDriver in conftest.pyfixture for init/teardown
6Run the verification testOpen example.com and assert title

STEP 1: Verify Python Version (Selenium Python Setup Prerequisite)

First, confirm Python is installed.

python --version
# or
python3 --version

Expected output:

Python 3.11.5
⚠️ Python 3.8+ is recommended. Some Selenium 4 features don’t work on 3.7 or below. If Python isn’t installed, download it from python.org.

STEP 2: Create and Activate a Virtual Environment (venv) [Python Environment Setup]

Virtual environments keep package dependencies isolated per project. Always use one in production.

Create the virtual environment

# Create project folder
mkdir selenium-project
cd selenium-project

# Create virtual environment
python -m venv venv

Activate the virtual environment

OSCommand
Windowsvenv\Scripts\activate
Mac / Linuxsource venv/bin/activate

Once activated, your prompt will show (venv) at the start.

(venv) $ 

STEP 3: Install Selenium, webdriver-manager, and pytest (Selenium Python Installation)

With Selenium 4, webdriver-manager automates ChromeDriver version management. No manual downloads required.

pip install selenium webdriver-manager pytest

Verify the installation:

pip list | grep -E "selenium|webdriver|pytest"

# Expected output
pytest             7.4.0
selenium           4.18.1
webdriver-manager  4.0.1
💡 Pro Tip: Save your installed packages with pip freeze > requirements.txt. Team members can recreate the exact same environment with pip install -r requirements.txt.
💡 Note: Using a code editor like VS Code with the Python and Pylance extensions installed makes code completion and debugging significantly more efficient.

STEP 4: Set Up Project Structure (pytest Structure)

Set up a clean project structure from the start.

selenium-project/
├── venv/                  # virtual environment (don't commit to Git)
├── tests/
│   ├── conftest.py        # fixture definitions
│   └── test_sample.py     # test file
├── requirements.txt       # package list
└── pytest.ini            # pytest config

Create pytest.ini

[pytest]
testpaths = tests
addopts = -v

STEP 5: Configure Selenium WebDriver (conftest.py)

Centralizing WebDriver initialization and teardown in a conftest.py fixture is the production best practice.

# tests/conftest.py
import pytest
from selenium import webdriver
from selenium.webdriver.chrome.service import Service
from webdriver_manager.chrome import ChromeDriverManager

@pytest.fixture(scope="function")
def driver():
    """Fixture that launches and quits Chrome WebDriver"""
    options = webdriver.ChromeOptions()
    # options.add_argument("--headless")  # Recommended OFF at first (see browser in action)
    # Turn this ON for CI/CD environments
    options.add_argument("--no-sandbox")            # For Linux/CI (not needed locally)
    options.add_argument("--disable-dev-shm-usage") # For Linux/CI (not needed locally)
    options.add_argument("--window-size=1920,1080")

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

    yield driver  # test runs here

    driver.quit()  # close browser after test

💡 Key Points

  • Keep --headless off to start — watching the browser actually move makes debugging much easier
  • Once everything’s verified, turn --headless on for CI/CD compatibility
  • scope="function" starts and stops the browser for each test — the safest option to prevent state leaking between tests

STEP 6: Write and Run the Verification Test (pytest)

We’ll use example.com for the verification test — it’s far more stable than Google, which can trigger CAPTCHAs or redirects depending on your region.

# tests/test_sample.py
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_example_title(driver):
    """Verify example.com title is retrieved correctly"""
    driver.get("https://example.com")
    assert "Example Domain" in driver.title

def test_example_heading(driver):
    """Wait for heading to be visible, then verify (production-level pattern)"""
    driver.get("https://example.com")
    # WebDriverWait: wait up to 10s until the element is visible (production standard)
    # visibility_of_element_located = in DOM AND visible on screen
    heading = WebDriverWait(driver, 10).until(
        EC.visibility_of_element_located((By.TAG_NAME, "h1"))
    )
    assert heading.is_displayed()

Run the tests

pytest

Sample output

========================== test session starts ==========================
platform darwin -- Python 3.11.5, pytest-7.4.0, selenium-4.18.1
collected 2 items

tests/test_sample.py::test_example_title    PASSED  [ 50%]
tests/test_sample.py::test_example_heading  PASSED  [100%]

========================== 2 passed in 3.21s ===========================
✅ 2 passed means your environment is fully set up! webdriver-manager handled the ChromeDriver download automatically — no manual steps required.

💡 Pro Tip: Why use WebDriverWait?

  • Using driver.find_element() alone can throw NoSuchElementException if the element hasn’t loaded yet
  • visibility_of_element_located (in DOM AND visible on screen) is more reliable than presence_of_element_located (in DOM only) — it tests what actually matters
  • Once your environment is working, mastering this wait pattern is your most important next step

⚠️ Common Errors and Solutions

① SessionNotCreatedException: Chrome version mismatch

Chrome and ChromeDriver versions don’t match.

# Solution: webdriver-manager handles this automatically
# If the cache is stale, upgrade it
pip install --upgrade webdriver-manager

② ModuleNotFoundError: No module named ‘selenium’

The virtual environment isn’t activated, or selenium was installed outside it.

# Solution: activate the virtual environment first, then reinstall
source venv/bin/activate  # Mac/Linux
venv\Scripts\activate     # Windows
pip install selenium webdriver-manager

③ No tests collected (collected 0 items)

The file or function name doesn’t start with test_.

# NG — missing test_ prefix
def check_example(driver):

# OK
def test_example_title(driver):

④ TimeoutException / NoSuchElementException

You’re trying to access an element before it’s rendered. Add an explicit wait.

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

# Wait up to 10 seconds until the element is visible
element = WebDriverWait(driver, 10).until(
    EC.visibility_of_element_located((By.TAG_NAME, "h1"))
)

Selenium vs Playwright: Which Should You Use?

For anyone deciding between the two:

AspectSeleniumPlaywright
HistorySince 2004 — industry standardSince 2020 — newer
Job / client demandSignificantly higherGrowing
Setup complexityModerate (needs Driver)Simple (auto-install)
Execution speedSlightly slowerFaster
Browser supportChrome · Firefox · Edge · SafariChrome · Firefox · WebKit
Best forExisting projects · Upwork clientsNew projects · modern dev
💡 Bottom line: For Upwork projects and maintaining existing systems, Selenium is essential. For brand-new projects, Playwright is more efficient. Being fluent in both increases your market value significantly.

FAQ

Q. What’s the difference between Selenium 3 and Selenium 4?

Selenium 4 (released 2021) changed how WebDriver management works. Code from Selenium 3 often uses webdriver.Chrome(executable_path=...) — this syntax is deprecated in version 4. This article is written for Selenium 4. Using webdriver-manager handles both versions automatically.

Q. What is headless mode?

Headless mode runs tests in the background without opening a visible browser window. It’s required in CI/CD environments (like GitHub Actions) because there’s no display. For local development, turning it off so you can watch the browser is strongly recommended — especially when debugging.

Q. Does this work with Firefox?

Yes. webdriver-manager supports GeckoDriver (the Firefox driver) as well. Use from webdriver_manager.firefox import GeckoDriverManager to get the same automatic management for Firefox.

In production, webdriver-manager has been the standard for ChromeDriver management for years. Before making the switch, version mismatches were a constant source of setup failures on client projects. After adopting webdriver-manager, environment setup issues dropped to near zero. Every new Selenium project now starts with this exact configuration.

Follow this guide step by step and you won’t get stuck on environment setup.

📋 Summary

  • Selenium × Python setup follows 5 steps: venv → pip install → conftest.py → write tests → run
  • webdriver-manager automates ChromeDriver version management — no more version mismatch errors
  • WebDriver init and teardown belongs in a conftest.py fixture — the production standard
  • Use --headless off locally, then turn it on for CI/CD
  • Selenium has the most job postings and client projects of any test automation tool — essential for Upwork

Once those 2 tests show PASSED, your environment is ready. From here, add more test cases and work toward login form testing and the Page Object Model pattern as your next steps.

Copied title and URL