What pytest-playwright is
pytest-playwright is the official plugin that connects Playwright for Python to Pytest. Instead of launching and closing browsers yourself, you request fixtures:
page: a fresh page in a fresh browser context for every test.context,browser,browser_name: the layers underneath, when you need them.- Command-line flags for browser choice, headed mode, base URL, tracing, screenshots and video.
If you are new to Playwright in Python, start with the Playwright Python tutorial; this guide focuses on the Pytest side.
Install pytest-playwright
python -m venv .venv source .venv/bin/activate # Windows: .venv\Scripts\activate pip install pytest-playwright playwright install # downloads Chromium, Firefox and WebKit
Tip: on a fresh Linux CI image use playwright install --with-deps chromium to install only the browser you need plus its system libraries.
Your first Playwright Pytest test
Pytest finds files named test_*.py. Ask for the page fixture by naming it as an argument:
import re
from playwright.sync_api import Page, expect
def test_has_title(page: Page):
page.goto("https://playwright.dev/")
expect(page).to_have_title(re.compile("Playwright"))
def test_get_started_link(page: Page):
page.goto("https://playwright.dev/")
page.get_by_role("link", name="Get started").click()
expect(page.get_by_role("heading", name="Installation")).to_be_visible()
Run pytest. Both tests run headless in Chromium, each in its own isolated context. Use expect(...) rather than a bare assert: expect retries until the condition is met, while assert page.is_visible(...) checks once and causes flaky failures.
pytest-playwright command-line flags
| Flag | What it does |
|---|---|
--headed | Show the browser window |
--browser firefox | Pick an engine; repeat the flag to run on several |
--browser-channel chrome | Use branded Chrome or msedge |
--base-url URL | Lets page.goto("/login") resolve against an environment |
--slowmo 500 | Pause 500 ms between actions |
--device "iPhone 13" | Emulate a device |
--tracing retain-on-failure | Keep a trace zip for failed tests |
--screenshot only-on-failure | Screenshot on failure |
--video retain-on-failure | Video of failed tests |
--output DIR | Where artifacts go (default test-results) |
Put the flags you always want in pytest.ini so nobody has to remember them:
[pytest] addopts = --browser chromium --tracing retain-on-failure --screenshot only-on-failure base_url = https://staging.example.com
Open a saved trace with playwright show-trace test-results/<test>/trace.zip. The Trace Viewer tutorial shows what to look for.
Built-in fixtures and their scope
| Fixture | Scope | Use it for |
|---|---|---|
page | function | Almost every test |
context | function | Multiple tabs, cookies, permissions |
browser | session | Creating your own contexts |
browser_name | session | Branching on the current engine |
browser_context_args | session | Default options for every context |
browser_type_launch_args | session | Launch options such as proxies |
Custom fixtures in conftest.py
conftest.py is where shared setup lives. Two fixtures cover most projects: default context options, and a logged-in page.
import os
import pytest
from playwright.sync_api import Browser
@pytest.fixture(scope="session")
def browser_context_args(browser_context_args):
# Extend the plugin's defaults instead of replacing them
return {**browser_context_args, "viewport": {"width": 1280, "height": 720}, "locale": "en-US"}
@pytest.fixture(scope="session")
def auth_state(browser: Browser, base_url, tmp_path_factory) -> str:
# Log in once per worker and save cookies + local storage
path = tmp_path_factory.mktemp("auth") / "state.json"
context = browser.new_context(base_url=base_url)
page = context.new_page()
page.goto("/login")
page.get_by_label("Email").fill(os.environ["QA_EMAIL"])
page.get_by_label("Password").fill(os.environ["QA_PASSWORD"])
page.get_by_role("button", name="Sign in").click()
page.wait_for_url("**/dashboard")
context.storage_state(path=path)
context.close()
return str(path)
@pytest.fixture
def logged_in_page(browser: Browser, base_url, auth_state):
context = browser.new_context(base_url=base_url, storage_state=auth_state)
page = context.new_page()
yield page
context.close()
Any test that takes logged_in_page starts on an authenticated session without repeating the login UI. The pattern is the same idea as storageState in the Node runner.
Parametrize and browser markers
import pytest
from playwright.sync_api import Page, expect
@pytest.mark.parametrize("term", ["locators", "assertions", "fixtures"])
def test_search_returns_results(logged_in_page: Page, term: str):
logged_in_page.goto("/search")
logged_in_page.get_by_role("searchbox").fill(term)
logged_in_page.keyboard.press("Enter")
expect(logged_in_page.get_by_role("article").first).to_be_visible()
@pytest.mark.skip_browser("webkit")
def test_file_download(page: Page): ...
@pytest.mark.only_browser("chromium")
def test_chrome_devtools_feature(page: Page): ...
Combine parametrize with several --browser flags and Pytest multiplies them: 3 terms × 3 engines = 9 test runs.
Run Playwright Pytest tests in parallel
pip install pytest-xdist pytest-rerunfailures pytest -n auto # one worker per CPU core pytest -n 4 --browser chromium --browser firefox pytest -n auto --reruns 1 # retry a failure once
Watch out: with xdist, a scope="session" fixture runs once per worker. Four workers mean four logins. Tests must not depend on each other or on shared mutable data, because they now run at the same time.
Retries hide problems as easily as they absorb them. If a test only passes on rerun, open its trace and fix the cause; the flaky tests guide lists the usual suspects.
Page objects with Pytest
from playwright.sync_api import Page
class LoginPage:
def __init__(self, page: Page):
self.page = page
self.email = page.get_by_label("Email")
self.password = page.get_by_label("Password")
self.sign_in = page.get_by_role("button", name="Sign in")
def goto(self):
self.page.goto("/login")
def login(self, email: str, password: str):
self.email.fill(email)
self.password.fill(password)
self.sign_in.click()
Expose page objects as fixtures (def login_page(page): return LoginPage(page)) so tests read like specifications. Keep expect calls in the tests.
pytest-playwright vs Playwright Test (Node)
| Need | pytest-playwright | Playwright Test |
|---|---|---|
| Fixtures | Pytest fixtures | Built-in fixtures |
| Parallel runs | pytest-xdist | Built in, with sharding |
| Retries | pytest-rerunfailures | Built in |
| HTML report | pytest-html | Built in |
| UI mode | No | Yes |
| Playwright Test Agents | No | Yes |
| Trace Viewer, codegen | Yes | Yes |
Pytest is the right call when your team already writes Python and has Pytest plugins it relies on. The Node runner ships more out of the box and gets new features, including the AI tooling, first.
How to learn Playwright with Pytest
Get the Playwright concepts solid first (locators, auto-waiting, web-first assertions, context isolation), then layer Pytest on top. Pytest itself is the easy part if you know Python.
Playwright + Claude AI & MCP Server: AI QA Automation 2026 teaches Playwright in JavaScript, not Python. It is still a useful next step: the locators, assertions, auto-waiting and Page Object Model you learn there are the same Playwright API with different casing, so everything carries over to Python. It then adds Claude Code, the Playwright MCP Server and Playwright Test Agents. See the course plan for what each section covers.
Frequently Asked Questions
What is pytest-playwright?
It is the official Pytest plugin for Playwright. It provides fixtures such as page, context and browser, plus command-line flags for browser choice, headed mode, tracing, screenshots and video.
How do I run Playwright Pytest tests in headed mode?
Run pytest --headed. Add --slowmo 500 to slow each action down so you can follow along.
How do I run Playwright Pytest tests in parallel?
Install pytest-xdist and run pytest -n auto. Each worker gets its own browser; session-scoped fixtures run once per worker, not once overall.
How do I share a logged-in state across Pytest tests?
Log in once in a session-scoped fixture, save context.storage_state(path=...), then create new contexts with storage_state= that path. Read credentials from environment variables, not from the code.
Should I use the sync or async Playwright API with Pytest?
Use the sync API for tests. It is simpler and pytest-playwright is built around it. Async tests need the separate pytest-playwright-asyncio plugin.
Does pytest-playwright have UI mode or Test Agents?
No. UI mode, the built-in HTML reporter and Playwright Test Agents are part of the Node test runner. With Pytest you use plugins such as pytest-html for reports and the Trace Viewer for debugging.
Asim Noaman
Sr. SQA Manager & AI Automation Engineer
18+ years in QA. Asim currently runs an 80+ engineer QA function at Tkxel and built a Testing Center of Excellence for a major Saudi bank. He builds AI testing agents with Playwright, Claude AI and the MCP Server at work, and teaches the same workflow in his courses.
Playwright + Claude AI Course on Udemy
Learn Playwright Once. Use It in Python Too.
The course teaches Playwright in JavaScript from zero: locators, assertions, hooks and the Page Object Model. The same API powers pytest-playwright with snake_case names. Then it adds Claude Code, the Playwright MCP Server and Playwright Test Agents. 107 lectures, 11.5 hours, rated 4.5★ from 140+ ratings, 570+ students.
- Playwright from scratch in JavaScript, no prior coding needed
- Page Object Model, hooks and timeouts
- Claude Code, custom QA subagents and the Playwright MCP Server
- Multi-agent workflows and Playwright Test Agents