Browse all tutorials →
Python Updated November 19, 2026 16 min read

Playwright Python Tutorial 2026: Setup, Pytest & Your First Test

A complete, hands-on Playwright Python guide using pytest. From pip install to cross-browser testing, tracing, Page Object Model, and CI/CD — everything a Python developer needs to start writing reliable end-to-end tests today.

Playwright Python is Microsoft's official Python version of Playwright, used with pytest to automate and test web apps in Chromium, Firefox and WebKit. To start, run pip install pytest-playwright, then playwright install, write a test_ function that takes the built-in page fixture, and run pytest. Auto-waiting, built-in tracing and first-class pytest fixtures make it a strong alternative to Selenium for new Python projects.

Playwright Python: key facts

Installpip install pytest-playwright then playwright install
Python version3.10 or newer for the current PyPI release
Test runnerpytest, with built-in page, context and browser fixtures
BrowsersChromium (default), Firefox, WebKit
Sync or asyncSync API by default; async tests via pytest-playwright-asyncio
Not in PythonPlaywright Test runner, UI Mode and Test Agents (Node.js only)

This tutorial assumes you know basic Python. No prior test automation experience needed.


Why Playwright + Python?

What you get with Playwright Python

  • Cross-browser: Chromium, Firefox, WebKit
  • Auto-waiting on every action (no sleeps)
  • Built-in pytest fixtures (page, browser, context)
  • Trace Viewer for visual debugging
  • Network interception & mocking
  • Screenshot & video on failure
  • Sync and async API variants
  • Parallel test execution via pytest-xdist

If you're coming from Selenium Python, Playwright eliminates the need for WebDriverWait, ChromeDriverManager, and most explicit waits. Every Playwright action automatically waits for the element to be actionable before interacting with it.

Know Python? The fastest route to AI-powered Playwright testing

Honest note: the course is taught in JavaScript, not Python. It starts from zero, so the syntax comes quickly, and it's where the AI tooling lives: Claude Code, the Playwright MCP Server, your own QA AI agent and Playwright Test Agents (Node.js only).

Enroll on Udemy →

Step 1: Install Playwright for Python

Two commands and you're ready:

Terminal
# Install Playwright + pytest plugin (Python 3.10+)
pip install pytest-playwright

# Download browser binaries (Chromium, Firefox, WebKit)
playwright install

Virtual environment recommended: Use python -m venv .venv and activate it before installing. This keeps Playwright isolated from your system Python.

Verify the installation:

Terminal
# Check Playwright version
playwright --version
# Prints the installed version, e.g. Version 1.6x.x

# Check pytest recognizes the plugin
pytest --fixtures
# Should list Playwright fixtures including 'page', 'browser', 'context'

Step 2: Project Structure

Create a clean project layout:

Project structure
my-playwright-project/
├── tests/
│   ├── __init__.py
│   ├── test_login.py
│   └── test_homepage.py
├── pages/                  # Page Object Model (optional)
│   ├── __init__.py
│   └── login_page.py
├── conftest.py             # Shared fixtures
├── pytest.ini              # pytest config
└── requirements.txt
pytest.ini
[pytest]
# Run tests in headed mode during development
addopts = --headed --slowmo 500

# For CI, remove --headed and --slowmo:
# addopts = --browser chromium

Step 3: Write Your First Test

The pytest-playwright plugin provides a page fixture automatically — no browser setup code needed:

tests/test_homepage.py
import re
from playwright.sync_api import Page, expect


def test_homepage_has_title(page: Page):
    """Verify the homepage loads with the correct title."""
    page.goto("https://playwright.dev/")

    # Assert the page title contains "Playwright"
    expect(page).to_have_title(re.compile("Playwright"))


def test_get_started_link(page: Page):
    """Click 'Get Started' and verify navigation."""
    page.goto("https://playwright.dev/")

    # Click the "Get started" link
    page.get_by_role("link", name="Get started").click()

    # Verify navigation to the intro page
    expect(page.get_by_role("heading", name="Installation")).to_be_visible()

Run it:

Terminal
# Run all tests
pytest

# Run a specific file
pytest tests/test_homepage.py

# Run with verbose output
pytest -v

Step 4: Locator Strategies

Playwright Python uses the same role-based locators as the TypeScript version. Always prefer these over CSS/XPath — they're more resilient to UI changes:

Python — locator strategies (best to worst)
# ✅ BEST: Role-based locators (accessible, resilient)
page.get_by_role("button", name="Submit")
page.get_by_role("link", name="Sign In")
page.get_by_role("heading", name="Dashboard")

# ✅ GOOD: Label and placeholder
page.get_by_label("Email address")
page.get_by_placeholder("Search...")

# ✅ GOOD: Test ID (requires data-testid in HTML)
page.get_by_test_id("checkout-button")

# ✅ OK: Text content
page.get_by_text("Add to Cart")

# ⚠️ AVOID: CSS selectors (brittle)
page.locator("#submit-btn")
page.locator(".form-container > button.primary")

Step 5: Assertions

Playwright's expect API auto-waits for conditions to be true (with a default 5-second timeout):

Python — common assertions
from playwright.sync_api import expect

# Page-level assertions
expect(page).to_have_url("https://example.com/dashboard")
expect(page).to_have_title("Dashboard")

# Element visibility
expect(page.get_by_role("alert")).to_be_visible()
expect(page.get_by_text("Loading")).to_be_hidden()

# Element content
expect(page.get_by_test_id("count")).to_have_text("42")
expect(page.get_by_role("textbox")).to_have_value("user@test.com")

# Element state
expect(page.get_by_role("button", name="Submit")).to_be_enabled()
expect(page.get_by_role("checkbox")).to_be_checked()

Step 6: A Real-World Login Test

tests/test_login.py
from playwright.sync_api import Page, expect


def test_successful_login(page: Page):
    """User can log in with valid credentials."""
    page.goto("http://localhost:3000/login")

    page.get_by_label("Email").fill("user@example.com")
    page.get_by_label("Password").fill("securePass123")
    page.get_by_role("button", name="Sign In").click()

    # Verify redirect to dashboard
    expect(page).to_have_url("http://localhost:3000/dashboard")
    expect(page.get_by_role("heading", name="Dashboard")).to_be_visible()


def test_invalid_credentials_show_error(page: Page):
    """Invalid login shows an error message."""
    page.goto("http://localhost:3000/login")

    page.get_by_label("Email").fill("wrong@example.com")
    page.get_by_label("Password").fill("wrongpass")
    page.get_by_role("button", name="Sign In").click()

    # Error message should appear
    expect(page.get_by_role("alert")).to_have_text("Invalid email or password")
    # Should stay on login page
    expect(page).to_have_url("http://localhost:3000/login")

Step 7: Shared Fixtures with conftest.py

Use conftest.py to set base URL, default timeouts, and shared authentication:

conftest.py
import pytest
from playwright.sync_api import Page


@pytest.fixture(scope="session")
def browser_context_args(browser_context_args):
    """Set default viewport and locale for all tests."""
    return {
        **browser_context_args,
        "viewport": {"width": 1280, "height": 720},
        "locale": "en-US",
    }


@pytest.fixture(scope="session")
def base_url():
    """Base URL for all page.goto() calls."""
    return "http://localhost:3000"

Authentication fixture: For apps behind login, save auth state once and reuse it. Run playwright codegen --save-storage=auth.json, log in manually, then load the state in conftest: browser_context_args["storage_state"] = "auth.json".

Step 8: Page Object Model

For larger test suites, encapsulate page interactions in classes:

pages/login_page.py
from playwright.sync_api import Page, expect


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.submit = page.get_by_role("button", name="Sign In")
        self.error = page.get_by_role("alert")

    def goto(self):
        self.page.goto("/login")
        return self

    def login(self, email: str, password: str):
        self.email.fill(email)
        self.password.fill(password)
        self.submit.click()

    def expect_error(self, message: str):
        expect(self.error).to_have_text(message)
tests/test_login.py — using POM
import re
from playwright.sync_api import Page, expect
from pages.login_page import LoginPage


def test_successful_login(page: Page):
    login = LoginPage(page).goto()
    login.login("user@example.com", "securePass123")
    expect(page).to_have_url(re.compile(r".*/dashboard"))

Step 9: Tracing & Debugging

Playwright's Trace Viewer is the most powerful debugging tool in test automation. Enable it on failure:

Terminal — run with tracing
# Record traces only on test failure
pytest --tracing retain-on-failure

# View the trace file
playwright show-trace test-results/test-login-chromium/trace.zip

The Trace Viewer shows a timeline of every action, DOM snapshots before and after each step, network requests, and console logs — making it trivial to understand why a test failed.

Step 10: Cross-Browser Testing

Terminal
# Run on all browsers
pytest --browser chromium --browser firefox --browser webkit

# Run on a specific browser
pytest --browser firefox

# Run headed (visible browser window)
pytest --headed

# Slow motion (great for demos)
pytest --headed --slowmo 1000

Step 11: Parallel Execution

Install pytest-xdist for parallel test execution:

Terminal
pip install pytest-xdist

# Run tests across 4 workers
pytest -n 4

# One worker per CPU core (recommended in the Playwright docs)
pytest --numprocesses auto

Step 12: CI/CD with GitHub Actions

.github/workflows/playwright.yml
name: Playwright Python Tests
on: [push, pull_request]
jobs:
  test:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4
      - uses: actions/setup-python@v5
        with:
          python-version: "3.12"
      - run: pip install pytest-playwright
      - run: playwright install --with-deps chromium
      - run: pytest --browser chromium --tracing retain-on-failure
      - uses: actions/upload-artifact@v4
        if: always()
        with:
          name: playwright-traces
          path: test-results/

Playwright Python vs JavaScript: What's Different?

The browser engine, locators, auto-waiting and Trace Viewer are the same in both. The tooling around them is not, and the gap matters most if you want to use AI to write tests:

FeaturePlaywright PythonPlaywright JavaScript/TypeScript
Test runnerpytest + pytest-playwrightPlaywright Test (@playwright/test)
Locators, auto-waiting, assertionsYes (get_by_role, expect)Yes (getByRole, expect)
Codegen and Trace ViewerYesYes
Parallel runsVia pytest-xdistBuilt in (workers, sharding)
UI ModeNoYes (npx playwright test --ui)
Test Agents (planner, generator, healer)NoYes (npx playwright init-agents)
Playwright MCP server with ClaudeUsable (the server runs on Node.js)Yes, and most examples target it

If your team already tests in Python, Playwright Python is an excellent choice and everything in this tutorial applies. If you want the full AI workflow, learning the JavaScript version is worth it, and your Python Playwright knowledge transfers almost line for line. The JavaScript Playwright automation tutorial builds the same kind of suite.

Playwright Python vs Selenium Python

If you're deciding between the two for a Python project in 2026:

  • Auto-waiting: Playwright auto-waits on every action. Selenium requires explicit WebDriverWait everywhere.
  • Setup: Playwright is 2 commands (pip install + playwright install). Selenium needs browser drivers + driver managers.
  • Speed: Playwright uses direct browser protocols. Selenium goes through WebDriver HTTP bridge (slower).
  • Debugging: Playwright has Trace Viewer. Selenium has manual logging.
  • Cross-browser: Playwright bundles exact browser versions. Selenium depends on system-installed drivers.
  • AI integration: Playwright has an official MCP Server that lets Claude drive a browser and write tests. Selenium has no official equivalent.

For a full comparison, see our Playwright vs Cypress vs Selenium 2026 guide.

Add the AI workflow Python can’t give you yet

You already know locators, fixtures and page objects. The course teaches the same ideas in JavaScript from scratch, then has Claude Code, the Playwright MCP Server and Test Agents plan, write and heal tests with you. 107 lectures, 30-day money-back guarantee.

Enroll on Udemy →

Frequently Asked Questions

Can I use Playwright with Python?

Yes. Microsoft maintains an official Playwright library for Python. Install it with pip install pytest-playwright, download browsers with playwright install, then write test_ functions that take the page fixture and run them with pytest. It supports Chromium, Firefox and WebKit, auto-waiting, network mocking and tracing.

How do I install Playwright in Python?

Create a virtual environment, run pip install pytest-playwright, then run playwright install to download Chromium, Firefox and WebKit. The current release on PyPI needs Python 3.10 or newer. You can also install with Poetry (poetry add pytest-playwright) or uv (uv add pytest-playwright).

Is Playwright Python as good as Playwright JavaScript?

For browser automation, almost. Both use the same engine, browsers, locators, auto-waiting and Trace Viewer. The differences are in tooling: Python runs on pytest, while the Node.js version has the Playwright Test runner, UI Mode and the Test Agents (planner, generator, healer), which are Node.js only. See the comparison table.

Is Playwright Python better than Selenium Python?

For most new projects, yes. Playwright Python auto-waits on every action, installs its own browsers with one command, includes tracing and video recording, and talks to browsers over a direct connection instead of the WebDriver HTTP protocol. Selenium still fits teams with a large existing Selenium suite or a Selenium Grid they rely on.

Should I learn Playwright with Python or JavaScript?

If your team's tests are already in Python, stay with Python. If you are choosing fresh, or you want the full AI workflow, JavaScript or TypeScript gives you more: the Test Agents and UI Mode only exist for Node.js, and most Playwright MCP examples target it. Your Python Playwright knowledge transfers almost line for line.


Asim Noaman, Playwright and Claude AI course instructor

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.

18+ Years in QA 80+ engineer QA function
Udemy Instructor 4.5★ · 140+ ratings · 570+ students
Anthropic Certificates Claude API · MCP
Connect on LinkedIn

Full profile →

Playwright + Claude AI Course

Go From Zero to a Production-Ready Playwright Framework

This guide gives you the Python foundation. The course is taught in JavaScript, not Python: it teaches Playwright from scratch (locators, assertions, hooks and the Page Object Model), then Claude Code, the Playwright MCP Server, your own QA AI agent and Playwright Test Agents. By the end, you'll have a real framework you can show to employers.

  • JavaScript and Playwright from absolute zero — no prior experience needed
  • Page Object Model and test architecture used on real teams
  • Claude AI generates your tests — you learn by reviewing and refining
  • Claude Code and the Playwright MCP Server for AI test generation
Start Learning on Udemy →