Run Web Automation Tests at Scale with Agentic AI

Generate tests with AI agents or automate test suites with Selenium, Playwright and other frameworks. Run tests in parallel on TestMu AI scalable cloud grid.

Playwright TestingTutorial

Playwright Python Tutorial: Examples, pytest, and AI Agents

Playwright Python tutorial with working examples: install, write pytest tests, run them in parallel on a cloud grid, and generate tests with AI agents via MCP.

Last Updated on:

A Playwright Python script can type a wrong password into a login form and still report a pass. The recorder-generated test later in this tutorial does exactly that, because a recorded script performs actions and checks nothing.

This Playwright Python tutorial builds a pytest suite that does check its results, then runs it on Chromium, Firefox, and WebKit, on a laptop and on the TestMu AI cloud grid. Every code sample ran on Playwright 1.63.0 on October 1, 2026, and each output block is the output I got; where I did not run a command as printed, the text says so.

The last section covers agentic AI workflows: Playwright MCP returning Python code, a coding agent writing a test from a skill, and the review each needs before you trust it.

Overview

To use Playwright with Python, install the pytest-playwright package with pip, download the browsers with playwright install, and write tests that take the page fixture. Playwright 1.63.0 requires Python 3.10 or later and drives Chromium, Firefox, and WebKit from one API, in synchronous and asyncio variants.

  • pytest-playwright: Playwright's official pytest plugin supplies page, context, and browser fixtures, a --browser flag for Chromium, Firefox, and WebKit, and tracing, video, and screenshot options. Installing it also installs Playwright for Python.
  • sync_playwright and async_playwright: Playwright Python has a synchronous API for tests and scripts and an asyncio API for working on several pages at once. The synchronous API raises an error when it is called inside a running event loop.
  • Locators and assertions: Playwright Python locators such as get_by_role() and get_by_label() find elements by role and label, and expect() assertions retry for 5 seconds by default before they fail.
  • TestMu AI cloud grid: A pytest-playwright suite runs on TestMu AI when its connect_options fixture returns the grid's WebSocket endpoint. The grid offers 3,000+ browser and OS combinations and can record video and console logs for each session.
  • Playwright MCP with Python: Started with --codegen python, the Playwright MCP server returns Python code such as page.get_by_role() calls for each action an AI agent takes. The planner, generator, and healer Test Agents support the Node.js test runner only.

What Is Playwright for Python?

Playwright for Python is the official Python version of Microsoft's open-source Playwright library. It automates Chromium, Firefox, and WebKit through one API, with a synchronous interface for tests and scripts and an asyncio interface for concurrent work. The pytest-playwright plugin adds fixtures, browser selection, and tracing.

For a quick visual walkthrough of this concept, watch the video below from TestMu AI.

Youtube thumbnail

Subscribe to the TestMu AI YouTube channel for more tutorials on testing and automation.

The current release is 1.63.0, published on September 15, 2026, according to the playwright package page on PyPI, and it requires Python 3.10 or later.

Playwright is built for end-to-end testing, where a test drives a full user journey through a real browser. It also has JavaScript, TypeScript, Java, and .NET versions with the same engines and locator model; the Playwright tutorial hub and the Playwright end-to-end testing guide cover the JavaScript side.

Python teams can also use Selenium and other frameworks; this list of automation testing tools compares them by language and license.

Why Use Playwright With Python?

Microsoft maintains the Python version in its own GitHub repository, microsoft/playwright-python, which has about 15,000 stars.

According to the Playwright documentation, the Python library gives a test suite:

  • Auto-waiting - each action waits until its element is visible, stable, and enabled, for up to 30 seconds by default, so tests need no sleep calls.
  • Retrying assertions - expect() re-checks its condition until it holds or 5 seconds pass.
  • Browser contexts - every test gets a fresh context with its own cookies and storage inside one browser process.
  • Three engines, one API - the same script runs on the Chromium, Firefox, and WebKit builds that playwright install downloads.
  • Built-in tooling - a code generator, a trace viewer, and an API request client ship with the library.
  • Agent-readable pages - role-based locators and aria snapshots describe a page the way an AI agent reads it, which the agentic section relies on.

A laptop gives Playwright one operating system and the bundled engines. TestMu AI's Automation Cloud runs the same Playwright scripts on 3,000+ browser and OS combinations with no grid to maintain, and the cloud grid section connects this tutorial's suite to it.

How to Install Playwright for Python

Playwright 1.63.0 needs Python 3.10 or later. Its PyPI metadata sets that floor, although the system requirements in the documentation still mention Python 3.8. The docs list Windows 11, macOS 14, Debian 12 and 13, and Ubuntu 22.04, 24.04, and 26.04 as supported systems.

Install in a Virtual Environment

These commands create an isolated environment, install the pytest plugin (which pulls in Playwright itself), and download the browsers. I ran them in PowerShell with Python 3.13.16. The browser builds were already in my cache, so playwright install had nothing left to download. On macOS or Linux, activate with source .venv/bin/activate instead.

python -m venv .venv
.venv\Scripts\activate
pip install pytest-playwright
playwright install

playwright install places one Chromium, one Firefox, and one WebKit build in a shared cache. For 1.63.0, playwright install --dry-run lists them as Chrome for Testing 153.0.8010.12, Firefox 155.0, and WebKit 26.6. The docs give equivalent Poetry and uv commands, and how to install Playwright covers the other languages.

Check the Installation

One command prints the library version, and another lists the browser builds each Playwright installation uses.

python -m playwright --version
python -m playwright install --list

Their output on my machine, one after the other:

Version 1.63.0

Playwright version: 1.63.0
  Browsers:
    W:\ms-playwright\chromium-1243
    W:\ms-playwright\chromium_headless_shell-1243
    W:\ms-playwright\ffmpeg-1011
    W:\ms-playwright\firefox-1543
    W:\ms-playwright\webkit-2359
    W:\ms-playwright\winldd-1007
  References:
    W:\Python313\Lib\site-packages\playwright\driver\package

Browsers lists the builds in the cache, and References lists the Playwright installations that use them, which makes leftover builds from older versions easy to spot. My cache is on a W: drive because I set the PLAYWRIGHT_BROWSERS_PATH environment variable; by default it sits under your user profile.

Install Options and Common Errors

The install command takes browser names and flags, as playwright install --help shows:

  • playwright install chromium - downloads one browser instead of three.
  • --with-deps - also installs the system packages the browsers need, which Linux CI images usually lack.
  • --only-shell - downloads only the headless Chromium shell, enough for headless CI runs.
  • --force - reinstalls a build that is already present.
  • --dry-run - prints what would be downloaded, and where, without downloading.

Common first-run errors and their fixes:

  • Executable doesn't exist - BrowserType.launch fails with this message when the browser build for the installed Playwright version is missing. Run playwright install again after every upgrade.
  • Import "playwright.sync_api" could not be resolved - a Pylance warning in VS Code when the editor points at an interpreter without Playwright. Select the .venv interpreter for the workspace.
  • Blocked downloads - on a network that blocks the browser download, run against an installed browser with pytest --browser-channel chrome, which passed for the first test in this tutorial.

Playwright Python Example: Your First Test

A useful first Playwright Python example opens a page, acts on it, and checks the result. This script searches the TestMu AI e-commerce playground, a demo store built for automation practice, for a product:

from playwright.sync_api import expect, sync_playwright

with sync_playwright() as p:
    browser = p.chromium.launch()
    page = browser.new_page()
    page.goto("https://ecommerce-playground.lambdatest.io/")
    page.get_by_role("textbox", name="Search For Products").fill("HTC")
    page.get_by_role("button", name="Search", exact=True).click()

    products = page.get_by_role("heading", name="HTC Touch HD")
    expect(products.first).to_be_visible()
    print(page.title(), "|", products.count(), "products")
    browser.close()

Saved as first_script.py and run with python first_script.py, it printed Search - HTC | 8 products.

sync_playwright() starts Playwright, launch() opens headless Chromium, and each get_by_role() call builds a locator that waits for its element before acting. The expect() line is a retrying assertion: it waits until a matching product heading is visible, so the count on the next line reads a loaded page.

The Same Check as a pytest Test

pytest-playwright removes the launch and close code by handing each test a ready page. The same check as a test file, test_search.py:

from playwright.sync_api import Page, expect


def test_search_lists_matching_products(page: Page):
    page.goto("https://ecommerce-playground.lambdatest.io/")
    page.get_by_role("textbox", name="Search For Products").fill("HTC")
    page.get_by_role("button", name="Search", exact=True).click()

    expect(page).to_have_title("Search - HTC")
    products = page.get_by_role("heading", name="HTC Touch HD")
    expect(products.first).to_be_visible()

Output of pytest test_search.py:

=========================== test session starts ===========================
platform win32 -- Python 3.13.16, pytest-9.1.1, pluggy-1.6.0
rootdir: W:\playwright-python-demo
plugins: base-url-2.1.0, playwright-0.9.0, xdist-3.8.0
collected 1 item

test_search.py .                                                     [100%]

=========================== 1 passed in 10.89s ============================

Sync vs Async API in Playwright Python

Everything so far uses the synchronous API. The asyncio API has the same methods behind await, and it lets one process work on several pages at once:

import asyncio

from playwright.async_api import async_playwright

BASE = "https://ecommerce-playground.lambdatest.io/index.php?route="
ROUTES = ["account/login", "account/register", "product/special"]


async def main():
    async with async_playwright() as p:
        browser = await p.chromium.launch()
        pages = [await browser.new_page() for _ in ROUTES]
        visits = [pg.goto(BASE + r) for pg, r in zip(pages, ROUTES)]
        await asyncio.gather(*visits)
        print([await pg.title() for pg in pages])


asyncio.run(main())

The script loaded the three pages concurrently and printed ['Account Login', 'Register Account', 'Special Offers']. Keep the synchronous API for pytest tests, because the plugin's fixtures are synchronous and async tests need the separate pytest-playwright-asyncio package.

The two do not mix: calling sync_playwright() inside a running event loop fails with "It looks like you are using Playwright Sync API inside the asyncio loop. Please use the Async API instead." The Python asyncio tutorial explains event loops and gather().

Using Playwright Python With pytest

The pytest-playwright plugin is the test runner the Playwright team documents for Python. It supplies fixtures and command-line options, so test files hold only test logic. For the JavaScript and TypeScript runner, the equivalent is covered in Playwright fixtures. If pytest itself is new to you, start with the pytest tutorial.

Fixtures

  • page - a new page in a new browser context for each test.
  • context - the browser context behind that page, also created per test.
  • new_context - a factory for extra contexts, for tests that need two users at once.
  • browser and browser_name - the browser shared by the whole session, and its name as a string.
  • browser_context_args and connect_options - fixtures you override to set context options or to connect to a remote browser, which the cloud grid section uses.

Command-Line Options

OptionEffectDefault
--browserRuns on chromium, firefox, or webkit; repeat it to run on severalchromium
--headedShows the browser windowheadless
--browser-channelUses an installed browser such as chrome or msedgebundled build
--slowmoDelays every operation by the given milliseconds0
--tracingRecords a trace: on, off, or retain-on-failureoff
--videoRecords video: on, off, or retain-on-failureoff
--screenshotCaptures a screenshot: on, off, or only-on-failureoff
--outputSets the folder for traces, videos, and screenshotstest-results

The plugin reference adds one caveat: these options apply only to the built-in browser, context, and page fixtures. A context you create yourself with browser.new_context() does not inherit them.

Cross-Browser Runs

Repeating --browser runs every test once per engine:

pytest test_search.py --browser chromium --browser firefox --browser webkit
=========================== test session starts ===========================
platform win32 -- Python 3.13.16, pytest-9.1.1, pluggy-1.6.0
rootdir: W:\playwright-python-demo
plugins: base-url-2.1.0, playwright-0.9.0, xdist-3.8.0
collected 3 items

test_search.py ...                                                   [100%]

=========================== 3 passed in 34.77s ============================

Traces and Screenshots on Failure

The --tracing retain-on-failure and --screenshot only-on-failure flags keep evidence when a test fails. My first version of the search test asserted on the first level-4 heading, which turned out to be the store's Filter panel, and failed with this report:

E       AssertionError: Locator expected to have text 'HTC Touch HD'
E       Actual value: Filter 
E       Call log:
E         - Expect "to_have_text" get_by_role("heading", level=4).first with timeout 5000ms
E         - waiting for get_by_role("heading", level=4).first
E           14 × locator resolved to <h4 class="mb-0">Filter</h4>
E              - unexpected value "Filter"
E       
E       Aria snapshot:
E       - heading "Filter" [level=4]

The call log shows the assertion retrying for 5 seconds, and the aria snapshot shows what the locator matched. With both flags set, the run left a screenshot and a trace in the output folder:

test-results/test-wrong-heading-py-test-first-heading-is-a-product-chromium/test-failed-1.png
test-results/test-wrong-heading-py-test-first-heading-is-a-product-chromium/trace.zip

Pass the zip path to playwright show-trace to step through the actions, DOM snapshots, and network calls of the failed test.

Austin Siewert

Austin Siewert

Co-Founder, Steadfast Systems

Discovered @TestMu AI yesterday. Best browser testing tool I've found for my use case. Great pricing model for the limited testing I do 👏

3M+ Devs and QAs rely on TestMu AI

Deliver immersive digital experiences with Next-Generation Mobile Apps and Cross Browser Testing Cloud

Playwright Python Locators and Assertions

A locator describes how to find an element and is resolved again each time it is used, so it survives re-renders. The Playwright documentation recommends user-facing locators first, in roughly this order:

  • get_by_role() - matches the ARIA role and accessible name, as in page.get_by_role("button", name="Login").
  • get_by_label() - matches a form control by its label text, as in page.get_by_label("E-Mail Address").
  • get_by_placeholder() and get_by_text() - match placeholder text and visible text.
  • get_by_test_id() - matches a data-testid attribute, when the application provides one.
  • locator() - takes CSS or XPath, as in page.locator(".alert-danger"), for elements with no role or label to match.

The Playwright locators guide covers filtering and chaining in depth.

Strict Mode and Exact Matching

Locators are strict: an action on a locator that matches more than one element fails instead of picking one. The playground has a second, hidden search box for small screens, so the placeholder locator in this script fails:

from playwright.sync_api import Error, sync_playwright

with sync_playwright() as p:
    page = p.chromium.launch().new_page()
    page.goto("https://ecommerce-playground.lambdatest.io/")
    try:
        page.get_by_placeholder("Search For Products").fill("HTC")
    except Error as error:
        print(error)
Locator.fill: Error: strict mode violation: get_by_placeholder("Search For Products") resolved to 2 elements:
    1) <input value="" type="text" name="search" autocomplete="off" data-autocomplete="5" aria-label="Search For Products" placeholder="Search For Products" data-autocomplete_route="extension/maza/product/product/autocomplete"/> aka get_by_role("textbox", name="Search For Products")
    2) <input value="" type="text" name="search" aria-label="Search For Products" placeholder="Search For Products"/> aka locator("#entry_217836").get_by_placeholder("Search For Products")

Call log:
  - waiting for get_by_placeholder("Search For Products")

The error names both matches and suggests a locator for each one. get_by_role("textbox", name="Search For Products") matches only the visible box, because role locators skip hidden elements by default.

Name matching is a case-insensitive substring match unless you pass exact=True. In my first draft of the page object, get_by_role("heading", name="HTC Touch HD") also matched the results page heading "Search - HTC Touch HD", and the click that followed timed out after the default 30 seconds.

Web-First Assertions

expect() assertions retry until they pass or time out, which removes most manual waits. The ones this tutorial uses:

AssertionPasses When
expect(page).to_have_title()The page title equals the expected string
expect(locator).to_be_visible()The element is attached and visible
expect(locator).to_have_text()The element's text equals the expected string
expect(locator).to_contain_text()The element's text contains the expected substring
expect(locator).to_match_aria_snapshot()The element's accessibility tree contains the given structure

The Playwright assertions guide lists the rest, including negation and soft assertions.

Timeouts and Actionability

Per the Playwright documentation, actions such as click() and fill() wait up to 30 seconds for their element, and expect() retries for 5 seconds. Change them with page.set_default_timeout() and expect.set_options(timeout=...), or pass timeout= to a single call.

page.wait_for_timeout() is a fixed sleep that the docs reserve for debugging, so it does not make a flaky test stable. The Playwright timeouts guide explains each timeout layer.

Before an action, Playwright also checks that the element can receive it. On the playground's registration form, check() on the Privacy Policy checkbox timed out on all three engines because its styled label intercepts pointer events, so the page object in the next sections clicks the label text instead.

When a test depends on a backend call, the patterns in Playwright waitForResponse and Playwright mock API carry over to Python as page.expect_response() and page.route().

How Does the Playwright Code Generator Work?

playwright codegen opens a browser and an inspector window, records your clicks and typing, and writes the equivalent code. The --target python-pytest option emits a pytest test, and -o saves it to a file:

playwright codegen --target python-pytest -o test_recorded.py "https://ecommerce-playground.lambdatest.io/index.php?route=account/login"

I did not click through that window by hand. A script drove the same recorder (Playwright 1.63.0, python-pytest target) through a login attempt with a wrong password, and this is the file the recorder wrote:

import re
from playwright.sync_api import Page, expect


def test_example(page: Page) -> None:
    page.goto("https://ecommerce-playground.lambdatest.io/index.php?route=account/login")
    page.get_by_role("textbox", name="E-Mail Address").click()
    page.get_by_role("textbox", name="E-Mail Address").fill("nobody@example.com")
    page.get_by_role("textbox", name="Password").click()
    page.get_by_role("textbox", name="Password").fill("wrong-password")
    page.get_by_role("button", name="Login").click()

The recorder picked role-based locators, and pytest test_recorded.py reported 1 passed. It passed although the store rejected the login, because the recorder writes actions and adds an assertion only when you use its assert tools.

Treat the output as a draft: keep the locators, add an expect() for the outcome, and move repeated steps into a page object. The Playwright Inspector guide walks through the recorder toolbar and its assert tools.

Building an End-to-End Suite With the Page Object Model

A page object wraps one page's locators and actions in a class, so tests read as user steps and a changed locator is fixed in one file. The suite below covers registration, login, and add to cart on the playground, with four tests in three files.

Project Layout and Configuration

playwright-python-demo/
    pytest.ini
    accounts.py
    pages/
        register_page.py
        login_page.py
        store_page.py
    tests/
        conftest.py
        test_signup.py
        test_cart.py
        test_login.py

pytest.ini makes the pages package importable, points pytest at the tests folder, and sets a base URL so page objects can use relative paths. It also keeps a trace and a screenshot for any test that fails:

[pytest]
pythonpath = .
testpaths = tests
addopts =
    --base-url https://ecommerce-playground.lambdatest.io
    --tracing retain-on-failure
    --screenshot only-on-failure

Page Objects

pages/register_page.py fills the registration form. exact=True separates the Password field from Password Confirm, and the last locator before the button clicks the Privacy Policy label text:

from playwright.sync_api import Page


class RegisterPage:
    def __init__(self, page: Page):
        self.page = page
        self.warning = page.locator(".alert-danger")

    def register(self, email: str, password: str):
        self.page.goto("/index.php?route=account/register")
        self.page.get_by_label("First Name").fill("Test")
        self.page.get_by_label("Last Name").fill("User")
        self.page.get_by_label("E-Mail").fill(email)
        self.page.get_by_label("Telephone").fill("5550100200")
        self.page.get_by_label("Password", exact=True).fill(password)
        self.page.get_by_label("Password Confirm").fill(password)
        self.page.get_by_text("I have read and agree to the").click()
        self.page.get_by_role("button", name="Continue").click()

pages/login_page.py logs in. Both classes expose the store's warning banner, which has no ARIA role, through a CSS locator:

from playwright.sync_api import Page


class LoginPage:
    def __init__(self, page: Page):
        self.page = page
        self.warning = page.locator(".alert-danger")

    def login(self, email: str, password: str):
        self.page.goto("/index.php?route=account/login")
        self.page.get_by_label("E-Mail Address").fill(email)
        self.page.get_by_label("Password").fill(password)
        self.page.get_by_role("button", name="Login").click()

pages/store_page.py searches for a product, opens it, and adds it to the cart in one method. The success toast has the alert role, and cart scopes later lookups to the main content area:

from playwright.sync_api import Page


class StorePage:
    def __init__(self, page: Page):
        self.page = page
        self.toast = page.get_by_role("alert")
        self.cart = page.locator("#content")

    def add_to_cart(self, name: str):
        page = self.page
        page.goto("/")
        page.get_by_role("textbox", name="Search For Products").fill(name)
        page.get_by_role("button", name="Search", exact=True).click()
        title = page.get_by_role("heading", name=name, exact=True)
        title.first.get_by_role("link").click()
        page.get_by_role("button", name="Add to Cart").click()

The Playwright Page Object Model guide goes further into base classes and component objects.

Fixtures and Tests

accounts.py creates throwaway credentials with a unique example.com address, so a second run never collides with the first:

import uuid


def new_account():
    email = f"pw.py.{uuid.uuid4().hex[:10]}@example.com"
    return {"email": email, "password": "S3cure-pass"}

tests/conftest.py defines registered_user, a session-scoped fixture that registers one account per browser session, in its own context, and asserts that registration succeeded:

import pytest
from playwright.sync_api import expect

from accounts import new_account
from pages.register_page import RegisterPage


@pytest.fixture(scope="session")
def registered_user(browser, base_url):
    user = new_account()
    context = browser.new_context(base_url=base_url)
    page = context.new_page()
    RegisterPage(page).register(**user)
    expect(page).to_have_title("Your Account Has Been Created!")
    context.close()
    return user

The fixture passes base_url to new_context() by hand, because command-line options do not reach contexts you create yourself.

tests/test_signup.py covers a new registration and a rejected duplicate:

from playwright.sync_api import Page, expect

from accounts import new_account
from pages.register_page import RegisterPage


def test_register(page: Page):
    RegisterPage(page).register(**new_account())
    expect(page).to_have_title("Your Account Has Been Created!")


def test_duplicate_email(page: Page, registered_user):
    register_page = RegisterPage(page)
    register_page.register(**registered_user)
    expect(register_page.warning).to_contain_text(
        "E-Mail Address is already registered!"
    )
    expect(page).to_have_title("Register Account")

tests/test_cart.py logs in, adds a product to the cart, and checks the cart page:

from playwright.sync_api import Page, expect

from pages.login_page import LoginPage
from pages.store_page import StorePage


def test_add_to_cart(page: Page, registered_user):
    LoginPage(page).login(**registered_user)
    expect(page).to_have_title("My Account")

    store = StorePage(page)
    store.add_to_cart("HTC Touch HD")
    expect(store.toast).to_contain_text("Success: You have added")

    store.toast.get_by_role("link", name="View Cart").click()
    row = store.cart.get_by_role("row", name="HTC Touch HD")
    expect(row).to_be_visible()

tests/test_login.py checks that a wrong password is rejected:

from playwright.sync_api import Page, expect

from pages.login_page import LoginPage


def test_wrong_password(page: Page, registered_user):
    login_page = LoginPage(page)
    login_page.login(registered_user["email"], "not-the-password")
    expect(login_page.warning).to_contain_text("No match for E-Mail")

Running pytest in the project folder executed the four tests on local Chromium:

=========================== test session starts ===========================
platform win32 -- Python 3.13.16, pytest-9.1.1, pluggy-1.6.0
baseurl: https://ecommerce-playground.lambdatest.io
rootdir: W:\playwright-python-demo
configfile: pytest.ini
testpaths: tests
plugins: base-url-2.1.0, playwright-0.9.0, xdist-3.8.0
collected 4 items

tests\test_cart.py .                                                 [ 25%]
tests\test_login.py .                                                [ 50%]
tests\test_signup.py ..                                              [100%]

=========================== 4 passed in 55.02s ============================

Running Playwright Python Tests on a Cloud Grid

Local runs cover the browsers on one machine. A remote grid adds other operating systems and many sessions at once: TestMu AI hosts Playwright sessions on Windows and macOS machines and can record video and console logs for each one.

pytest-playwright has a documented hook for remote browsers, the connect_options fixture. When it returns a WebSocket endpoint, every built-in fixture uses the remote browser, and tests and page objects stay unchanged.

Grid Connection and Status Reporting

grid.py builds the endpoint. It starts with TARGETS, which maps each pytest-playwright browser name to a grid browser and platform:

import json
import os
from urllib.parse import quote

GRID = "wss://cdp.lambdatest.com/playwright?capabilities="
TARGETS = {
    "chromium": ("Chrome", "Windows 11"),
    "firefox": ("pw-firefox", "Windows 11"),
    "webkit": ("pw-webkit", "macOS Sequoia"),
}

The rest of grid.py assembles the capabilities. The credentials come from the LT_USERNAME and LT_ACCESS_KEY environment variables, which hold the username and access key from your TestMu AI account:

def endpoint(browser_name):
    browser, platform = TARGETS[browser_name]
    capabilities = {
        "browserName": browser,
        "browserVersion": "latest",
        "LT:Options": {
            "platform": platform,
            "build": "Playwright Python tutorial",
            "name": f"pytest on {browser}",
            "user": os.environ["LT_USERNAME"],
            "accessKey": os.environ["LT_ACCESS_KEY"],
            "video": True,
            "console": True,
        },
    }
    return GRID + quote(json.dumps(capabilities))

The root conftest.py begins with a --grid option and a connect_options fixture that returns the endpoint when the option is set:

import json

import pytest

import grid


def pytest_addoption(parser):
    parser.addoption("--grid", action="store_true",
                     help="run on the TestMu AI cloud grid")


@pytest.fixture(scope="session")
def connect_options(pytestconfig, browser_name):
    if pytestconfig.getoption("--grid"):
        return {"endpoint": grid.endpoint(browser_name)}

The dictionary key has to be endpoint, the name of the first parameter of connect() in Playwright 1.63.0. The wsEndpoint key shown in the plugin reference raised "TypeError: BrowserType.connect() got an unexpected keyword argument" in my run.

A grid session stays marked as completed, with no pass or fail, until the test reports a status. The second half of conftest.py reports one per browser session and marks it failed if any test in that session failed:

@pytest.fixture(scope="session", autouse=True)
def grid_status(request, browser, pytestconfig):
    failed_before = request.session.testsfailed
    yield
    if pytestconfig.getoption("--grid"):
        passed = request.session.testsfailed == failed_before
        arguments = {"status": "passed" if passed else "failed"}
        action = {"action": "setTestStatus", "arguments": arguments}
        page = browser.new_page()
        page.evaluate("_ => {}", "lambdatest_action: " + json.dumps(action))

Running the Suite on the Grid

With the two variables exported in the shell, pytest --grid ran the same four tests on Chrome on Windows 11:

=========================== test session starts ===========================
platform win32 -- Python 3.13.16, pytest-9.1.1, pluggy-1.6.0
baseurl: https://ecommerce-playground.lambdatest.io
rootdir: W:\playwright-python-demo
configfile: pytest.ini
testpaths: tests
plugins: base-url-2.1.0, playwright-0.9.0, xdist-3.8.0
collected 4 items

tests\test_cart.py .                                                 [ 25%]
tests\test_login.py .                                                [ 50%]
tests\test_signup.py ..                                              [100%]

====================== 4 passed in 78.72s (0:01:18) =======================

The terminal output looks the same as a local run, so I read the result back from the grid. grid_sessions.py asks the grid's Automation API for the most recent sessions:

import os
import sys

import requests

auth = (os.environ["LT_USERNAME"], os.environ["LT_ACCESS_KEY"])
url = "https://api.lambdatest.com/automation/api/v1/sessions"
sessions = requests.get(url, auth=auth, params={"limit": sys.argv[1]})
for s in sessions.json()["data"]:
    print(s["name"], s["platform"], s["status_ind"], f"{s['duration']}s",
          sep=" | ")

python grid_sessions.py 1 printed pytest on Chrome | win11 | passed | 65s. A deliberately failing test in the same setup showed up as failed, which confirms that the status comes from the tests.

The capabilities turn on video and console logs only. With network logging also enabled, the pw-firefox session in my runs started with a 0x0 viewport and every click timed out as outside of the viewport, so I leave it off when Firefox is in the matrix.

Note

Note: TestMu AI runs your Playwright Python suite on Chrome, Firefox, and WebKit sessions across Windows and macOS, with video and console logs for every session. start free

Running Playwright Python Tests in Parallel

pytest-xdist runs tests in several worker processes, and each worker starts its own browser. Install it and pass a worker count:

pip install pytest-xdist
pytest -n 4

Timings From My Runs

Wall-clock times reported by pytest for this suite on October 1, 2026. They vary from run to run with the playground's response time:

CommandBrowsersTestsTime
pytestLocal Chromium455.02 s
pytest -n 4Local Chromium, 4 workers430.15 s
pytest --gridGrid Chrome, 1 session478.72 s
pytest --grid -n 4Grid Chrome, 4 sessions443.39 s
pytest --grid with three --browser flagsGrid Chrome, Firefox, WebKit12225.92 s
pytest --grid -n 6 with three --browser flagsGrid Chrome, Firefox, WebKit, 6 sessions1264.81 s

On four tests, four workers took a little over half the sequential time, because every worker pays for its own browser start and its own registered_user fixture. On the three-browser matrix, six workers cut the run to less than a third of the sequential time.

Three Browsers in Parallel on the Grid

The matrix run combines --grid, a worker count, and one --browser flag per engine, followed by the session check:

pytest --grid -n 6 --browser chromium --browser firefox --browser webkit
python grid_sessions.py 6
=========================== test session starts ===========================
platform win32 -- Python 3.13.16, pytest-9.1.1, pluggy-1.6.0
baseurl: https://ecommerce-playground.lambdatest.io
rootdir: W:\playwright-python-demo
configfile: pytest.ini
testpaths: tests
plugins: base-url-2.1.0, playwright-0.9.0, xdist-3.8.0
created: 6/6 workers
6 workers [12 items]

............                                                         [100%]
====================== 12 passed in 64.81s (0:01:04) ======================

The six sessions the grid recorded for that run, two per browser:

pytest on Chrome | win11 | passed | 42s
pytest on pw-webkit | sequoia | passed | 32s
pytest on pw-webkit | sequoia | passed | 26s
pytest on pw-firefox | win11 | passed | 31s
pytest on Chrome | win11 | passed | 24s
pytest on pw-firefox | win11 | passed | 46s

Parallel Run Pitfalls

  • Session fixtures are per worker - registered_user runs once in each worker, so workers never share an account. Tests that need shared data must create it per worker or use unique values.
  • Base URL and xdist - with base_url set as its own key in pytest.ini, the workers in my run did not receive it and every navigation failed with "Cannot navigate to invalid URL". Passing --base-url through addopts, as the file above does, fixed it.
  • Grid concurrency - each worker holds one grid session, so the worker count is capped by the parallel sessions in your plan.

To run Playwright Python tests at scale on the TestMu AI HyperExecute grid, which splits a suite across cloud machines from one YAML file, see the Playwright Python on HyperExecute documentation.

For worker and shard tuning, read Playwright parallel testing, and for pipeline setup, Playwright CI/CD.

Agentic AI Workflows for Playwright Python

An AI agent either writes Playwright test code from a prompt or drives a browser through tool calls and turns what it did into code. Both routes work for Python, with limits that differ by tool.

Agent Tooling That Works With Python

Checked on October 1, 2026 against the Playwright documentation, the Playwright MCP README, the Kane CLI reference, and my own runs:

ToolUsable in a Python ProjectCode It Produces
Playwright MCP serverYes; it is a Node.js package that runs beside the projectPython with --codegen python; TypeScript by default
Playwright CLI (playwright-cli)Yes; also a Node.js packageJavaScript snippets only in version 0.1.22
Playwright Test Agents (planner, generator, healer)No; they target the Node.js test runner, and the Python docs have no page for themTypeScript tests
playwright codegenYespython, python-async, and python-pytest targets, recorded with no AI involved
TestMu AI Playwright skillYes; it has Python patterns for coding agentspytest-playwright tests with TestMu AI cloud settings
Kane CLIYes; it runs natural-language objectives in a browserPlaywright code export, Python by default

The Playwright Agents guide covers the planner, generator, and healer for teams that also keep a TypeScript suite.

Playwright MCP With Python Code Generation

The Playwright MCP server lets an agent such as Claude Code, Cursor, or GitHub Copilot control a browser through tool calls. Its README documents a --codegen option that accepts typescript, python, java, csharp, or none, so one extra argument in the client configuration makes it answer in Python:

{
  "mcpServers": {
    "playwright": {
      "command": "npx",
      "args": ["@playwright/mcp@latest", "--codegen", "python"]
    }
  }
}

I started the server (@playwright/mcp 0.0.83) with those arguments, plus --headless, from a small MCP client script and called browser_navigate, browser_type twice, and browser_click on the playground login page. The code in the four tool results, in order:

page.goto("https://ecommerce-playground.lambdatest.io/index.php?route=account/login")
page.get_by_role("textbox", name="E-Mail Address").fill("nobody.mcp.probe@example.com")
page.get_by_role("textbox", name="Password").fill("wrong-password")
page.get_by_role("button", name="Login").click()

Those lines paste straight into a pytest test and use the same role-based locators as the page objects above. Without the option, the same calls returned JavaScript in the form await page.getByRole(...). The Playwright MCP guide covers client setup and the full tool list.

The Page Snapshot an Agent Reads

MCP works from an accessibility snapshot of the page rather than screenshots: each element has a role, a name, and a ref the model can act on. Playwright Python prints a snapshot in the same format with aria_snapshot(mode="ai"):

from playwright.sync_api import sync_playwright

URL = "https://ecommerce-playground.lambdatest.io/index.php"

with sync_playwright() as p:
    page = p.chromium.launch().new_page()
    page.goto(URL + "?route=account/login")
    print(page.locator("#content form").aria_snapshot(mode="ai"))
    whole_page = page.aria_snapshot(mode="ai")
    print(len(whole_page), "characters for the whole page")
- generic [ref=e1]:
  - generic [ref=e2]:
    - generic [ref=e3]: E-Mail Address
    - textbox "E-Mail Address" [ref=e4]
  - generic [ref=e5]:
    - generic [ref=e6]: Password
    - textbox "Password" [ref=e7]
    - link "Forgotten Password" [ref=e8] [cursor=pointer]:
      - /url: https://ecommerce-playground.lambdatest.io/index.php?route=account/forgotten
  - button "Login" [ref=e9] [cursor=pointer]
14301 characters for the whole page

The login form is ten lines, but the whole page came to 14301 characters, which an agent reads each time it asks for a full snapshot. That is why the Playwright docs point coding agents to the command-line playwright-cli, whose commands "avoid loading large tool schemas and verbose accessibility trees into the model context".

The snapshot format doubles as an assertion. This test fails when the structure of the login form changes, and it passed against the playground:

from playwright.sync_api import Page, expect


def test_login_form_structure(page: Page):
    page.goto("/index.php?route=account/login")
    expect(page.locator("#content form")).to_match_aria_snapshot("""
      - textbox "E-Mail Address"
      - textbox "Password"
      - link "Forgotten Password"
      - button "Login"
    """)

A Test Written by a Coding Agent With a Skill

Agent skills are folders of instructions and code patterns that a coding agent loads when a task matches them. TestMu AI publishes a Playwright skill with Python patterns for pytest and the cloud grid. This command installed it for Claude Code in an empty project and reported "Installed 1 skill":

npx -y agentskillsforall add https://github.com/LambdaTest/agent-skills.git --skill playwright-skill --agent claude-code -y --copy

I then gave a Claude Code agent one prompt in that project, with an instruction to write the files without running them:

Write a Playwright test in Python with pytest for https://ecommerce-playground.lambdatest.io/index.php?route=account/login. It should log in with a wrong password and check that the store shows a warning. Run it on TestMu AI cloud, Chrome on Windows 11.

The agent read the skill, inspected the login page with curl, and wrote four files: a pytest.ini, a requirements file, a 95-line conftest.py with cloud fixtures and status reporting, and tests/test_login.py, which opens with these lines:

"""Negative login test for the ecommerce playground, run on TestMu AI cloud."""
import uuid

from playwright.sync_api import Page, expect

LOGIN_URL = "https://ecommerce-playground.lambdatest.io/index.php?route=account/login"

The test function follows:

def test_login_with_wrong_password_shows_warning(cloud_page: Page):
    # The store locks an e-mail address for an hour after 5 failed logins and then
    # shows a different warning, so every run uses a fresh address.
    email = f"wrong-password-{uuid.uuid4().hex[:12]}@example.com"

    cloud_page.goto(LOGIN_URL)
    cloud_page.get_by_label("E-Mail Address").fill(email)
    cloud_page.get_by_label("Password").fill("not-the-right-password")
    cloud_page.get_by_role("button", name="Login", exact=True).click()

    # Submitting reloads the whole page (same URL), so give the warning as long as
    # a navigation gets instead of the 5 second assertion default.
    warning = cloud_page.get_by_text("Warning:")
    expect(warning).to_be_visible(timeout=30_000)
    expect(warning).to_contain_text("No match for E-Mail Address and/or Password.")

I ran the files unchanged, and the test passed on the first run, with the grid recording the session as passed:

=========================== test session starts ===========================
platform win32 -- Python 3.13.16, pytest-9.1.1, pluggy-1.6.0 -- W:\Python313\python.exe
cachedir: .pytest_cache
rootdir: W:\agent-skill-demo
configfile: pytest.ini
plugins: base-url-2.1.0, playwright-0.9.0, xdist-3.8.0
collecting ... collected 1 item

tests/test_login.py::test_login_with_wrong_password_shows_warning PASSED [100%]

=========================== 1 passed in 23.06s ============================

The agent added details the prompt did not ask for. It posted failed logins with curl, found that the store locks an address after five failed attempts, and generated a fresh address for each run. It also URL-encoded the capabilities and added status reporting, both of which the skill's Python fixture example leaves out.

Its fixtures are custom, though. cloud_page bypasses the plugin's page fixture, so --browser, tracing, and the connect_options setup from this tutorial do not apply, and its capabilities enable the network logging that broke Firefox in my matrix. A review has to catch differences like these.

Let Claude Code write Playwright tests that actually pass.

Playwright

Review Checklist for Agent-Written Tests

  • Outcome assertions - the recorded login in this tutorial passed with a wrong password. Reject any generated test that has no expect() on the result of its last action.
  • Locator matches - strict mode violations and substring matches appear only when the test runs, so run generated code once before you read it closely.
  • Test data - a fixed email works on the first run and collides on the second. Ask the agent for unique data per run, as the new_account() helper produces.
  • Every target browser - run the result on the full matrix before merging, because a test that passes on Chromium can still fail on Firefox or WebKit.

If you would rather describe a flow than prompt for code, KaneAI authors tests from natural-language steps and exports them as Playwright, Selenium, Cypress, or Appium code. Kane CLI runs the same kind of objective from the terminal and can export a completed run as a Playwright script, with Python as the default language.

Conclusion

Start with first_script.py, turn it into a pytest test, and give every test an assertion on its outcome before you add the next one.

When the suite from this Playwright Python tutorial needs browsers or operating systems your machine lacks, add grid.py and the --grid option and run it on TestMu AI's Playwright testing cloud. The Python with Playwright documentation lists the browser names and capabilities the grid accepts.

Testing from the terminal? Kane CLI by TestMu AI lets SDETs and developers plan, write, run and debug tests from the command line.

To run your first test, start free, or
for a full walkthrough of the product.

Author

...

Salman Khan

Blogs: 136

  • Twitter
  • Linkedin

Salman is a Test Automation Evangelist and Community Contributor at TestMu AI, with over 6 years of hands-on experience in software testing and automation. He has completed his Master of Technology in Computer Science and Engineering, demonstrating strong technical expertise in software development, testing, AI agents and LLMs. He is certified in KaneAI, Automation Testing, Selenium, Cypress, Playwright, and Appium, with deep experience in CI/CD pipelines, cross-browser testing, AI in testing, and mobile automation. Salman works closely with engineering teams to convert complex testing concepts into actionable, developer-first content. Salman has authored 120+ technical tutorials, guides, and documentation on test automation, web development, and related domains, making him a strong voice in the QA and testing community.

Reviewer

...

Srinivasan Sekar

Reviewer

  • Linkedin

Srinivasan Sekar is Director of Engineering at TestMu AI, where he leads engineering and open-source initiatives behind the Selenium and Appium automation grid and owns TestMu AI's MCP Server. A committer to Appium and a contributor to Selenium, WebdriverIO, Taiko, and AppiumTestDistribution, he brings over 15 years of experience in quality engineering and open-source technologies. He is the author of the Apress book 'The MCP Standard: A Developer's Guide to Building Universal AI Tools with the Model Context Protocol,' a Certified Kubernetes and Cloud Native Associate, and an international conference speaker. Before TestMu AI he spent over eight years at Thoughtworks as a Principal Consultant and Quality Architect. Srinivasan holds a B.Tech in Information Technology from Anna University.

Playwright Python Tutorial FAQs

Did you find this page helpful?

More Related Blogs

TestMu AI forEnterprise

Get access to solutions built on Enterprise
grade security, privacy, & compliance

  • Advanced access controls
  • Advanced data retention rules
  • Advanced Local Testing
  • Premium Support options
  • Early access to beta features
  • Private Slack Channel
  • Unlimited Manual Accessibility DevTools Tests