Playwright Pytest Integration: Step-by-Step Guide (2026) | TechSarvam

1. Introduction to Playwright Pytest Integration

Modern web applications need reliable automated testing across browsers. Manual testing is useful, but repeating the same checks after every application change takes time. This is where browser automation frameworks become valuable.

Playwright Pytest integration combines Playwright’s browser automation capabilities with Pytest’s test execution and organisation features. Together, they help QA Engineers and SDETs create maintainable automated test scripts for web applications.

Playwright supports Chromium, Firefox, and WebKit. Pytest provides test discovery, fixtures, parametrization, setup and teardown, and reporting integrations.

In this tutorial, you will learn how to install and configure Playwright with Pytest, write your first browser automation test, use built-in fixtures, implement the Page Object Model (POM), execute tests in parallel, and configure CI/CD pipelines.

The examples use Python and the official pytest-playwright plugin.

2. What Are Playwright and Pytest?

What is Playwright?

Playwright is an open-source browser automation framework. It allows testers to interact with web applications using Python, JavaScript, TypeScript, Java, and .NET.

You can use it to:

What is Pytest?

Pytest is a Python testing framework. It helps developers and QA Engineers write and execute test cases with simple Python functions.

For example:

def test_addition():

    assert 10 + 5 == 15

Pytest automatically discovers test functions that follow its naming conventions, such as functions beginning with test_.

Why integrate Playwright with Pytest?

Playwright controls the browser, while Pytest manages test execution.

PlaywrightPytest
Browser automationTest execution
Locators and actionsTest discovery
Browser contexts and pagesFixtures
Web-first assertionsParametrization
Screenshots and tracesTest organisation and plugins

The official pytest-playwright plugin connects these tools and provides built-in browser fixtures and command-line options.

3. Prerequisites and Python Environment Setup

Before starting, install the following tools:

  1. Python.
  2. pip package manager.
  3. Visual Studio Code or another Python editor.
  4. A terminal or command prompt.
  5. An internet connection for package and browser downloads.

Use a Python version supported by the current Playwright release. Check the official installation documentation when setting up a new environment.

Verify Python:

Windows:

python –version

macOS and Linux:

python3 –version

Check pip:

python -m pip –version

Create a project folder:

mkdir playwright-pytest-project

cd playwright-pytest-project

Create a virtual environment:

Windows:

python -m venv venv

venv\Scripts\activate

macOS and Linux:

python3 -m venv venv

source venv/bin/activate

A virtual environment isolates project dependencies. It helps prevent conflicts between different Python automation projects.

4. Installing Playwright and Pytest

Install Playwright and the official Pytest plugin:

python -m pip install pytest-playwright

The plugin installs Playwright as a dependency. You can also install both packages explicitly:

python -m pip install playwright pytest-playwright

Install the browser binaries:

playwright install

This downloads the supported browser engines.

To install a specific browser:

playwright install chromium

playwright install firefox

playwright install webkit

On supported Linux environments, install the browser system dependencies as well:

playwright install –with-deps

Verify the installed packages:

python -m pip show playwright

python -m pip show pytest-playwright

python -m pip show pytest

Important: The Python package and browser binaries are separate installation steps. If a browser executable is missing, run playwright install again.

5. Creating a Project Structure and Configuration

A clean folder structure makes test automation easier to maintain.

Create the following structure:

playwright-pytest-project/

│

├── pages/

│   ├── __init__.py

│   └── home_page.py

│

├── tests/

│   ├── __init__.py

│   └── test_homepage.py

│

├── conftest.py

├── pytest.ini

├── requirements.txt

└── .gitignore

requirements.txt

Store your project dependencies:

pytest

pytest-playwright

pytest-html

pytest-xdist

For repeatable team builds, pin the tested package versions rather than relying indefinitely on unpinned dependencies.

pytest.ini

Create a configuration file:

[pytest]

testpaths = tests

addopts = -v

This tells Pytest to search for tests inside the tests folder and display detailed test results.

.gitignore

Avoid committing your virtual environment and generated files:

venv/

__pycache__/

.pytest_cache/

test-results/

report.html

6. Writing and Running the First Playwright Pytest Test

Let’s create a simple browser automation test.

Create tests/test_homepage.py:

from playwright.sync_api import expect

def test_playwright_homepage(page):

    page.goto(“https://playwright.dev”)

    expect(page).to_have_title(

        “Fast and reliable end-to-end testing for modern web apps | Playwright

    )

The page argument is a fixture supplied by the Playwright Pytest plugin.

The test opens the Playwright website and verifies its title.

Run the test:

pytest

Or:

python -m pytest

To run one file:

pytest tests/test_homepage.py

To run tests with a visible browser:

pytest –headed

To run tests in Chromium:

pytest –browser chromium

The title of a live website can change. If the assertion fails because the website content has been updated, inspect the current title and update the expected value.

7. Using Built-in Fixtures: page, browser, and context

Fixtures are one of the most useful features of Pytest. A fixture prepares an object or resource before a test and manages its lifecycle.

The Playwright Pytest plugin provides several built-in fixtures.

page fixture

The page fixture provides a browser page for a test.

def test_homepage(page):

    page.goto(“https://playwright.dev”)

    assert page.url.startswith(“https://playwright.dev”)

Each test that requests the standard page fixture receives an isolated page and browser context.

browser fixture

The browser fixture provides access to the launched browser instance.

def test_browser_launch(browser):

    page = browser.new_page()

    page.goto(“https://playwright.dev”)

    assert “playwright” in page.url

    page.close()

The plugin manages the browser lifecycle. Close pages or contexts that your test creates manually when they are no longer needed.

context fixture

A browser context is similar to an independent browser profile. It separates cookies, local storage, and other session information.

def test_context(context):

    page = context.new_page()

    page.goto(“https://playwright.dev”)

    assert page.title() != “”

The plugin also provides fixtures such as new_context, playwright, browser_type, and browser_name.

Use the fixture that matches your requirement. For normal UI tests, page is usually sufficient.

8. Managing Setup and Teardown with Pytest Fixtures and Hooks

In a real automation project, you may need to perform common actions before and after tests.

Examples include opening a starting URL, creating test data, logging in, and cleaning up resources.

You can define reusable fixtures in conftest.py.

import pytest

@pytest.fixture

def application_url():

    return “https://playwright.dev”

@pytest.fixture

def open_homepage(page, application_url):

    page.goto(application_url)

    yield page

Use the fixture in a test:

from playwright.sync_api import expect

def test_homepage_title(open_homepage):

    expect(open_homepage).to_have_title(

        “Fast and reliable end-to-end testing for modern web apps | Playwright”

    )

The yield statement separates setup from teardown. Code placed after yield runs when the fixture is cleaned up.

For example:

import pytest

@pytest.fixture

def sample_resource():

    print(“Setup: create resource”)

    yield “test-data”

    print(“Teardown: clean resource”)

Pytest also supports hooks such as pytest_runtest_makereport for custom reporting and failure handling. Use hooks when fixture behaviour alone is not sufficient.

Avoid creating unnecessary custom browser fixtures when the official plugin already provides the required functionality.

9. Locators, Assertions, and Test Parametrization

Working with locators

Locators identify elements on a web page.

Playwright provides user-friendly locator methods:

def test_navigation(page):

    page.goto(“https://playwright.dev”)

    page.get_by_role(

        “link”,

        name=”Get started”

    ).click()

Other useful locator methods include:

page.get_by_text(“Documentation”)

page.get_by_label(“Email”)

page.get_by_placeholder(“Enter your email”)

page.get_by_test_id(“submit-button”)

Prefer accessible locators such as roles and labels. They make tests easier to understand and maintain.

Using Playwright assertions

Playwright provides web-first assertions through expect().

from playwright.sync_api import expect

def test_page_heading(page):

    page.goto(“https://playwright.dev”)

    expect(

        page.get_by_role(“heading”, level=1)

    ).to_be_visible()

Web-first assertions automatically retry until the expected condition is satisfied or the timeout is reached.

You can also use standard Python assertions for ordinary values:

def test_url(page):

    page.goto(“https://playwright.dev”)

    assert “playwright.dev” in page.url

Use Playwright’s expect() for browser elements and page conditions. Use Python’s assert for normal Python values.

Test parametrization

Parametrization allows the same test to execute with different input values.

import pytest

from playwright.sync_api import expect

@pytest.mark.parametrize(

    “url”,

    [

        “https://playwright.dev”,

        “https://www.python.org”

    ]

)

def test_website_title(page, url):

    page.goto(url)

    expect(page).to_have_title(

        __import__(“re”).compile(“.+”)

    )

For clearer code, you can import re normally:

import re

import pytest

from playwright.sync_api import expect

@pytest.mark.parametrize(

    “url”,

    [

        “https://playwright.dev”,

        “https://www.python.org”

    ]

)

def test_website_title(page, url):

    page.goto(url)

    expect(page).to_have_title(re.compile(“.+”))

This example checks that both websites have a non-empty page title.

Parametrization is especially useful for login scenarios, search inputs, browser compatibility checks, and regression testing.

10. Page Object Model with Playwright and Pytest

The Page Object Model is a design pattern that separates page locators and browser actions from test logic.

It improves code reuse and makes automation frameworks easier to maintain.

For this example, we will create a page object for the Playwright website.

Step 1: Create pages/home_page.py

from playwright.sync_api import Page

class HomePage:

    def __init__(self, page: Page):

        self.page = page

        self.get_started_link = page.get_by_role(

            “link”,

            name=”Get started”

        )

    def open(self):

        self.page.goto(“https://playwright.dev”)

    def click_get_started(self):

        self.get_started_link.click()

Step 2: Create tests/test_homepage.py

from playwright.sync_api import expect

from pages.home_page import HomePage

def test_get_started_navigation(page):

    home = HomePage(page)

    home.open()

    home.click_get_started()

    expect(page).to_have_url(

        “https://playwright.dev/docs/intro”

    )

The page object contains the page locator and reusable action. The test contains the scenario and assertion.

This separation becomes valuable when your application has many pages and test cases.

For a larger framework, you can add:

For more advanced architecture, explore the Playwright Framework Design pillar on TechSarvam.

11. Parallel Execution, Screenshots, and HTML Reporting

Parallel test execution

Install the xdist plugin:

pip install pytest-xdist

Run tests using four workers:

pytest -n 4

Or let xdist choose the number of workers:

pytest -n auto

Parallel execution can reduce test duration. However, tests should not depend on shared mutable data or interfere with each other’s accounts and sessions.

Cross-browser testing

Run tests in Chromium:

pytest –browser chromium

Run tests in Firefox:

pytest –browser firefox

Run tests in WebKit:

pytest –browser webkit

Run the same suite across all three:

pytest –browser chromium –browser firefox –browser webkit

Screenshots on failure

Use the plugin’s screenshot option:

pytest –screenshot only-on-failure

Tracing

Enable traces for failed tests:

pytest –tracing retain-on-failure

You can inspect a saved trace using:

playwright show-trace path/to/trace.zip

The trace helps you review browser actions, page snapshots, and network activity.

HTML reporting

Install the reporting plugin:

pip install pytest-html

Generate a report:

pytest –html=report.html –self-contained-html

Open report.html in a browser to review the execution results.

Keep reports and failure artifacts as CI pipeline artifacts when you need to investigate failures after a build.

12. GitHub Actions and Jenkins CI/CD Integration

Running tests locally is useful, but professional QA teams also execute automated test suites in CI/CD pipelines.

GitHub Actions

Create this file:

.github/workflows/playwright-tests.yml

name: Playwright Pytest Tests

on:

  push:

    branches: [main]

  pull_request:

    branches: [main]

jobs:

  test:

    runs-on: ubuntu-latest

    steps:

      – name: Checkout code

        uses: actions/checkout@v4

      – name: Set up Python

        uses: actions/setup-python@v5

        with:

          python-version: “3.12”

      – name: Install dependencies

        run: |

          python -m pip install –upgrade pip

          pip install -r requirements.txt

      – name: Install browsers

        run: playwright install –with-deps

      – name: Run tests

        run: pytest –html=report.html –self-contained-html

      – name: Upload report

        if: always()

        uses: actions/upload-artifact@v4

        with:

          name: pytest-report

          path: report.html

This workflow checks out the project, installs Python dependencies, downloads browser binaries, executes tests, and uploads the HTML report.

Jenkins integration

Create a Jenkinsfile for a Linux-based Jenkins agent:

pipeline {

    agent any

    stages {

        stage(‘Checkout’) {

            steps {

                checkout scm

            }

        }

        stage(‘Install’) {

            steps {

                sh ”’

                    python3 -m venv venv

                    . venv/bin/activate

                    pip install -r requirements.txt

                    playwright install –with-deps

                ”’

            }

        }

        stage(‘Test’) {

            steps {

                sh ”’

                    . venv/bin/activate

                    pytest –html=report.html –self-contained-html

                ”’

            }

        }

    }

    post {

        always {

            archiveArtifacts artifacts: ‘report.html’,

                             allowEmptyArchive: true

        }

    }

}

This example assumes the Jenkins agent has Python and the permissions required to install browser dependencies. Adapt the commands for Windows agents.

For larger projects, also configure test result publishing, screenshots, traces, and environment-specific test data.

13. Common Errors and Troubleshooting

Error: No module named playwright

Cause: Playwright is not installed in the active Python environment.

Solution:

python -m pip install pytest-playwright

Error: Fixture ‘page’ not found

Cause: The Pytest plugin may not be installed or loaded.

Solution:

python -m pip install pytest-playwright

pytest –help

Check that the Playwright options appear in the help output.

Error: Browser executable not found

Cause: Browser binaries are missing.

Solution:

playwright install

Error: Browser dependencies missing on Linux

Solution:

playwright install –with-deps

Error: Tests fail only during parallel execution

Cause: Tests may share accounts, files, or application data.

Solution: Use independent test data, isolated accounts, and unique resource names. Do not assume tests will execute in a fixed order.

Error: Element is not visible or clickable

Cause: The locator may identify the wrong element, or the element may not be ready.

Solution: Verify the locator and use Playwright’s auto-waiting and web-first assertions. Avoid adding arbitrary time.sleep() calls.

Leave a Comment

Your email address will not be published. Required fields are marked *