Playwright Python Parallel Execution: Step-by-Step Guide (2026)

1. Introduction to Playwright Python Parallel Execution

As web applications become more complex, automation teams need to execute larger test suites in less time. Running every test one after another can make regression testing slow, especially when a project contains hundreds of test cases.

Playwright Python parallel execution helps solve this problem by allowing multiple automated tests to run simultaneously.

Playwright is a browser automation framework that supports Chromium, Firefox, and WebKit. When combined with Pytest and pytest-xdist, it can distribute independent browser tests across multiple worker processes.

For example, an e-commerce application may have separate tests for login, product search, shopping cart, and checkout. Instead of waiting for each test to finish sequentially, you can distribute them across multiple workers.

In this tutorial, you will learn how to configure parallel execution, manage browser contexts, avoid race conditions, run cross-browser tests, and integrate your automation suite with GitHub Actions and Jenkins.

2. What Is Parallel Test Execution and Why Is It Important?

Parallel test execution means running multiple test cases at the same time rather than executing them one by one.

Consider a test suite containing 60 independent tests. If each test takes approximately five seconds, sequential execution could take around five minutes, excluding setup and teardown overhead.

Running tests across multiple workers can reduce the total time, depending on machine resources and test design.

Benefits of parallel execution

  • Faster test execution: Multiple independent tests run simultaneously.
  • Quicker regression testing: Teams receive feedback sooner.
  • Improved CI/CD efficiency: Pull requests can be validated faster.
  • Better resource utilization: Available CPU resources can be used more effectively.
  • Frequent test execution: Teams can run larger suites more often.
  • Earlier defect detection: Problems can be identified before application changes are released.

However, adding more workers does not always make tests faster. Browser automation consumes memory and CPU resources. Too many workers can overload the machine or the application under test.

3. Prerequisites and Python Playwright Installation

Before starting this Playwright Python parallel execution tutorial, prepare the following tools:

ToolPurpose
Python 3.11 or newerProgramming language
PlaywrightBrowser automation
PytestTest runner
pytest-playwrightPlaywright fixtures for Pytest
pytest-xdistParallel test execution
GitVersion control
VS CodeCode editor

Step 1: Create a project folder

mkdir playwright-parallel

cd playwright-parallel

Step 2: Create a virtual environment

python -m venv venv

Activate it on Windows:

venv\Scripts\activate

On macOS or Linux:

source venv/bin/activate

Step 3: Install the required packages

pip install playwright pytest pytest-playwright pytest-xdist

Install Chromium:

playwright install chromium

For Linux CI environments, install the browser’s operating-system dependencies too:

playwright install –with-deps chromium

To install all supported browser engines:

playwright install

Verify the installation:

pytest –version

python -m playwright –version

Your environment is ready to execute Playwright tests with Pytest.

4. Understanding Sequential vs Parallel Execution

Before configuring workers, understand the difference between sequential and parallel execution.

Sequential execution

In sequential execution, the test runner executes one test after another.

pytest

Example:

def test_homepage(page):

    page.goto(“https://example.com”)

    assert “Example” in page.title()

def test_login_page(page):

    page.goto(“https://www.saucedemo.com/”)

    assert “Swag Labs” in page.title()

The second test starts after the first test finishes.

Parallel execution

Parallel execution distributes tests across multiple worker processes.

pytest -n 2

Here, -n 2 starts two workers.

Illustrative execution:

Sequential:

Test 1 → Test 2 → Test 3 → Test 4

Parallel with two workers:

Worker 1: Test 1 → Test 3

Worker 2: Test 2 → Test 4

The actual assignment and order can vary. Tests should not depend on which worker executes them or when they run.

5. Running Tests in Parallel Using Pytest-xdist

pytest-xdist is a Pytest plugin that distributes tests across multiple worker processes.

Step 1: Create the project structure

playwright-parallel/

│

├── tests/

│   ├── test_home.py

│   ├── test_login.py

│   └── test_products.py

│

├── conftest.py

├── pytest.ini

└── requirements.txt

Step 2: Create independent test cases

Create tests/test_home.py:

from playwright.sync_api import expect

def test_homepage_title(page):

    page.goto(“https://example.com”)

    expect(page).to_have_title(“Example Domain”)

def test_homepage_heading(page):

    page.goto(“https://example.com”)

    expect(

        page.get_by_role(

            “heading”,

            name=”Example Domain”

        )

    ).to_be_visible()

Create tests/test_login.py:

from playwright.sync_api import expect

def test_login_page_title(page):

    page.goto(“https://www.saucedemo.com/”)

    expect(page).to_have_title(“Swag Labs”)

def test_username_field(page):

    page.goto(“https://www.saucedemo.com/”)

    expect(

        page.locator(“[data-test=’username’]”)

    ).to_be_visible()

Create tests/test_products.py:

from playwright.sync_api import expect

def test_products_after_login(page):

    page.goto(“https://www.saucedemo.com/”)

    page.locator(

        “[data-test=’username’]”

    ).fill(“standard_user”)

    page.locator(

        “[data-test=’password’]”

    ).fill(“secret_sauce”)

    page.locator(

        “[data-test=’login-button’]”

    ).click()

    expect(

        page.get_by_text(“Products”, exact=True)

    ).to_be_visible()

These tests use the SauceDemo practice application. Each test navigates independently and does not depend on another test’s browser session.

Step 3: Run tests in parallel

pytest -n 2

Pytest-xdist creates two worker processes and distributes the collected tests between them.

You can also run:

pytest -n 4

This starts four workers.

6. Configuring Workers with pytest -n

The -n option controls how many worker processes pytest-xdist starts.

Fixed worker count

pytest -n 2

Runs tests with two workers.

pytest -n 4

Runs tests with four workers.

Choose the worker count based on available CPU, memory, browser workload, and application capacity.

Automatic worker count

pytest -n auto

The auto option asks pytest-xdist to select the number of workers based on the available CPU count.

It is convenient for local execution, but browser tests can consume substantial memory. A fixed worker count may be more stable in resource-limited CI environments.

Test distribution options

Pytest-xdist supports several distribution strategies.

OptionDescription
–dist=loadDefault strategy; distributes tests among workers
–dist=loadscopeGroups tests by module for functions and by class for methods
–dist=loadfileRuns tests from the same file in one worker
–dist=loadgroupKeeps tests with the same xdist_group marker together
–dist=workstealMoves pending tests between workers to help balance workloads

Examples:

pytest -n 4 –dist=load

pytest -n 4 –dist=loadscope

pytest -n 4 –dist=loadfile

For loadgroup, mark related tests and select the distribution strategy:

import pytest

@pytest.mark.xdist_group(“checkout”)

def test_checkout():

    pass

Run:

pytest -n 4 –dist=loadgroup

Grouping tests does not automatically make shared state safe. Prefer independent test cases wherever possible.

7. Parallel Browser Testing Across Chromium, Firefox, and WebKit

Playwright supports three major browser engines:

  • Chromium
  • Firefox
  • WebKit

Install all browser engines:

playwright install

Run tests across all three:

pytest –browser chromium –browser firefox –browser webkit

Combine browser selection with parallel workers:

pytest -n 3 –browser chromium –browser firefox –browser webkit

The Playwright Pytest plugin runs the selected browser configurations, while xdist distributes the collected tests across workers.

This can create a large number of browser sessions. Begin with fewer workers and monitor CPU and memory usage.

For larger projects, a CI matrix with separate browser jobs can make browser-specific failures easier to identify.

8. Using Independent Browser Contexts and Fixtures

Test isolation is essential for reliable parallel execution.

A browser context represents an isolated browser session. It has its own cookies, local storage, and session state.

The pytest-playwright plugin provides fixtures such as page, context, and browser. Each test using the standard page fixture receives a page managed through the plugin’s browser lifecycle.

Example:

from playwright.sync_api import expect

def test_first_session(page):

    page.goto(“https://example.com”)

    expect(page).to_have_title(“Example Domain”)

def test_second_session(page):

    page.goto(“https://www.saucedemo.com/”)

    expect(page).to_have_title(“Swag Labs”)

If you need to test two users in one test, create separate contexts:

def test_two_users(browser):

    context_one = browser.new_context()

    context_two = browser.new_context()

    page_one = context_one.new_page()

    page_two = context_two.new_page()

    page_one.goto(“https://example.com”)

    page_two.goto(“https://www.saucedemo.com/”)

    assert “Example” in page_one.title()

    assert “Swag Labs” in page_two.title()

    context_one.close()

    context_two.close()

This approach is useful for administrator and customer permission testing.

9. Managing Test Data, Shared Resources, and Test Isolation

Parallel execution can introduce race conditions.

A race condition happens when multiple tests access or modify the same resource at the same time, producing unexpected results.

For example, two tests might update the same customer record. One test could overwrite the data created by the other.

Common problems

Generate unique test data

Use a unique identifier for each test:

import uuid

def create_unique_username():

    return f”user_{uuid.uuid4().hex[:8]}”

Use worker-specific resources

Pytest-xdist provides the worker_id fixture. It returns identifiers such as gw0 and gw1. In a non-distributed run, it returns master.

def test_worker_data(worker_id):

    username = f”test_user_{worker_id}”

    print(username)

For unique identifiers across an entire distributed test run, combine testrun_uid with worker_id:

def test_unique_reference(worker_id, testrun_uid):

    reference = f”{testrun_uid}_{worker_id}”

    print(reference)

In real projects, also clean up temporary records safely. One worker should never delete data another worker still needs.

10. Complete Real-World Parallel Execution Project

Let’s combine the concepts into a practical project.

Step 1: Create requirements.txt

playwright

pytest

pytest-playwright

pytest-xdist

pytest-html

Install dependencies:

pip install -r requirements.txt

playwright install chromium

Step 2: Configure pytest.ini

[pytest]

testpaths = tests

addopts = -v

Step 3: Create conftest.py

Use the standard Playwright fixtures and add a reusable application URL:

import pytest

@pytest.fixture(scope=”session”)

def application_url():

    return “https://www.saucedemo.com/”

Step 4: Create tests/test_parallel.py

from playwright.sync_api import expect

def test_login_page(page, application_url):

    page.goto(application_url)

    expect(page).to_have_title(“Swag Labs”)

def test_username_field(page, application_url):

    page.goto(application_url)

    expect(

        page.locator(“[data-test=’username’]”)

    ).to_be_visible()

def test_password_field(page, application_url):

    page.goto(application_url)

    expect(

        page.locator(“[data-test=’password’]”)

    ).to_be_visible()

def test_successful_login(page, application_url):

    page.goto(application_url)

    page.locator(

        “[data-test=’username’]”

    ).fill(“standard_user”)

    page.locator(

        “[data-test=’password’]”

    ).fill(“secret_sauce”)

    page.locator(

        “[data-test=’login-button’]”

    ).click()

    expect(

        page.get_by_text(“Products”, exact=True)

    ).to_be_visible()

Step 5: Execute the project

Sequential execution:

pytest

Parallel execution with two workers:

pytest -n 2

Automatic worker selection:

pytest -n auto

Generate an HTML report:

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

This project demonstrates independent browser tests distributed across multiple worker processes.

11. Parallel Execution in GitHub Actions and Jenkins

Parallel execution is useful in continuous integration because regression tests can run automatically after code changes.

GitHub Actions example

Create .github/workflows/parallel-tests.yml:

name: Playwright Parallel Tests

on:

  push:

    branches: [main]

  pull_request:

    branches: [main]

permissions:

  contents: read

jobs:

  test:

    runs-on: ubuntu-latest

    steps:

      – name: Checkout code

        uses: actions/checkout@v4

      – name: Setup Python

        uses: actions/setup-python@v5

        with:

          python-version: “3.12”

      – name: Install dependencies

        run: |

          pip install -r requirements.txt

      – name: Install Chromium

        run: |

          python -m playwright install –with-deps chromium

      – name: Run parallel tests

        run: |

          pytest -n 2 \

            –browser chromium \

            –html=report.html \

            –self-contained-html

      – name: Upload report

        if: always()

        uses: actions/upload-artifact@v4

        with:

          name: parallel-test-report

          path: report.html

          if-no-files-found: ignore

The workflow checks out the repository, installs Python dependencies and Chromium, and runs the test suite with two workers.

The HTML report is uploaded even when the test step fails.

Jenkins example

Create a Jenkinsfile in the project root:

pipeline {

    agent any

    stages {

        stage(‘Checkout’) {

            steps {

                checkout scm

            }

        }

        stage(‘Install Dependencies’) {

            steps {

                sh ”’

                    python3 -m venv venv

                    . venv/bin/activate

                    pip install -r requirements.txt

                    python -m playwright install –with-deps chromium

                ”’

            }

        }

        stage(‘Parallel Tests’) {

            steps {

                sh ”’

                    . venv/bin/activate

                    pytest -n 2 \

                      –browser chromium \

                      –html=report.html \

                      –self-contained-html

                ”’

            }

        }

    }

    post {

        always {

            archiveArtifacts(

                artifacts: ‘report.html’,

                allowEmptyArchive: true

            )

        }

    }

}

This example assumes a Linux Jenkins agent. The agent needs Python, Git, browser dependencies, and permission to install or access browser binaries.

Remember that pytest -n 2 creates two worker processes inside the Jenkins job. Jenkins can also execute separate jobs or pipeline stages in parallel, which is a different level of parallelism.

12. Reporting, Debugging, Common Errors, and Troubleshooting

Reporting helps QA Engineers understand which tests passed, failed, or need investigation.

Generate HTML and JUnit reports

Install the HTML reporting plugin:

pip install pytest-html

Generate an HTML report:

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

Generate JUnit XML:

pytest -n 2 –junitxml=results.xml

JUnit XML can be published by CI tools such as Jenkins.

Capture screenshots and traces

Capture screenshots for failed tests:

pytest -n 2 –screenshot=only-on-failure

Retain traces for failed tests:

pytest -n 2 –tracing=retain-on-failure

Upload the test-results directory as a CI artifact so the team can inspect debugging information.

Common errors and solutions

ProblemPossible solution
Worker crashesReduce workers and inspect memory usage
Browser launch failsInstall browser binaries and system dependencies
Random test failuresCheck shared data and race conditions
File or port conflictsUse unique resources per worker
CI tests time outCheck runner capacity and application response
Tests pass sequentially but fail in parallelRemove execution-order dependencies

When debugging, first run the failing test without xdist:

pytest tests/test_parallel.py -v

Then try one worker:

pytest -n 1

Increase the worker count gradually. This helps identify whether the problem comes from test logic, concurrency, or machine resources.

Leave a Comment

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