Playwright Python Cheat Sheet (pytest-playwright, 2026)

Everything from this course on one page, for quick revision and for the moment you forget the exact name of an option. Each block shows the Python syntax you need most often, with a link to the lesson that explains it. The examples use the SQA Tools practice sites, and the complete test at the end was run with Playwright 1.65 and pytest-playwright 0.10.

Advertisement

📖 What You’ll Learn: install and project commands, pytest-playwright command-line options, locators, actions, assertions and timeouts, waiting for events, fixtures and context options, devices, storage state, network routes and HAR, API requests, frames, dialogs, tabs, downloads, tracing and debugging, parallel runs, reports and a CI snippet.


📦 Install and Project

⌨️ Terminal

python -m venv .venv
.venv\Scripts\activate                      # macOS/Linux: source .venv/bin/activate
pip install pytest-playwright               # playwright + pytest + pytest-base-url
playwright install --with-deps chromium     # or: playwright install (all browsers)
playwright codegen https://sqatools.in/dummy-ecommerce-website/
# pytest.ini
[pytest]
addopts = --base-url https://sqatools.in --strict-markers -ra
markers =
    smoke: quick checks

Lessons: 2, 6, 7.


⌨️ pytest-playwright Options

Option Example
Browser(s) --browser firefox --browser webkit
Branded browser --browser-channel chrome / msedge
Watch it --headed --slowmo 500
Device --device "Pixel 7"
Base URL --base-url https://qa.example.com
Artifacts --tracing retain-on-failure --screenshot only-on-failure --video retain-on-failure --output test-results
Select -k login, -m smoke, --lf, -x, path::test_name
Parallel -n auto (pytest-xdist)
Retries --reruns 2 (pytest-rerunfailures)
Reports --html=report.html --self-contained-html, --alluredir=allure-results, --junitxml=junit.xml

🎯 Locators

page.get_by_role("button", name="Log in", exact=True)
page.get_by_label("Email")
page.get_by_placeholder("Search for t-shirts")
page.get_by_text("Coupon SAVE10 applied.")
page.get_by_test_id("cart-count")                  # data-testid
page.locator("#price-min")                         # CSS
page.locator("xpath=//table//tr[2]")               # XPath (last resort)

cards = page.get_by_test_id("product-card")
cards.filter(has_text="Wireless Earbuds").get_by_role("button", name="Add to cart")
cards.first, cards.last, cards.nth(2), cards.count(), cards.all()
page.frame_locator("#sampleIframe").get_by_role("link")

Lessons: 31, 32.


🖱️ Actions

page.goto("/dummy-ecommerce-website/#/login")      # relative to base_url
locator.click(); locator.dblclick(); locator.hover()
locator.fill("testuser"); locator.clear(); locator.press("Enter")
locator.press_sequentially("earbuds", delay=50)
locator.check(); locator.uncheck(); locator.set_checked(True)
locator.select_option("price-asc"); locator.select_option(label="Price: low to high")
locator.set_input_files("report.pdf")
locator.drag_to(target)
locator.tap()                                      # needs has_touch
page.keyboard.press("Control+A"); page.mouse.wheel(0, 500)

Lesson: 33.


✅ Assertions (auto-retrying)

from playwright.sync_api import expect

expect(page).to_have_url(re.compile(r"#/cart$"))
expect(page).to_have_title(re.compile("SQA Tools"))
expect(locator).to_be_visible() / to_be_hidden() / to_be_enabled() / to_be_checked()
expect(locator).to_have_text("−₹500") / to_contain_text("applied")
expect(locator).to_have_text(["A", "B"])           # list: count + order + text
expect(locator).to_have_value("2") / to_have_count(3) / to_have_attribute("aria-expanded", "true")
expect(locator).not_to_be_empty()
expect(locator).to_have_text("x", timeout=10_000)  # one assertion
expect.set_options(timeout=7_000)                  # all assertions
expect(api_response).to_be_ok()

Lessons: 37, 38.


Advertisement

⏳ Waiting for Events

with page.expect_response("**/api/products*") as info:
    page.get_by_role("button", name="Reload").click()
data = info.value.json()

with page.expect_request("**/echo") as req: ...
with page.expect_download() as dl: ...; dl.value.save_as("file.csv")
with page.expect_popup() as popup: ...; new_page = popup.value
page.on("dialog", lambda d: d.accept())
page.on("console", lambda m: print(m.type, m.text))
page.wait_for_url(re.compile("dashboard"))
locator.wait_for(state="visible")

🧩 Fixtures and Context Options

import pytest

@pytest.fixture(scope="session")
def browser_context_args(browser_context_args, playwright):
    return {**browser_context_args,
            **{k: v for k, v in playwright.devices["Pixel 7"].items() if k != "default_browser_type"},
            "locale": "en-IN", "timezone_id": "Asia/Kolkata",
            "geolocation": {"latitude": 18.52, "longitude": 73.85}, "permissions": ["geolocation"],
            "color_scheme": "dark"}

@pytest.fixture(scope="session")
def browser_type_launch_args(browser_type_launch_args):
    return {**browser_type_launch_args, "slow_mo": 100}

@pytest.mark.skip_browser("webkit")
@pytest.mark.only_browser("chromium")
@pytest.mark.browser_context_args(locale="hi-IN")

Lessons: 41, 42, 43, 50.


🔐 Login Once (storage state)

context.storage_state(path=".auth/user.json")                 # after logging in
browser.new_context(storage_state=".auth/user.json")          # start logged in
context.set_storage_state(".auth/user.json")                  # switch an existing context
context.add_init_script("sessionStorage.setItem('k', 'v')")   # sessionStorage is not saved

Lesson: 51.


🌐 Network

page.route("**/api/products*", lambda r: r.fulfill(json={"data": []}))
page.route("**/api/**", lambda r: r.fulfill(status=500))
page.route("**/*.{png,jpg}", lambda r: r.abort())
page.route(API, handler, times=1); page.unroute(API)

def handler(route):
    response = route.fetch()
    body = response.json(); body["data"][0]["price"] = 1
    route.fulfill(response=response, json=body)

page.route_from_har("api.har", url="**/api/**", update=True)    # record
page.route_from_har("api.har", url="**/api/**")                 # replay

Lessons: 52, 53.


🔌 API Testing

api = playwright.request.new_context(base_url="https://sqatools.in/wp-json/sqa-api/v1/",
                                     extra_http_headers={"X-API-Key": "sqa-key-12345"})
r = api.get("products", params={"category": "books"})
r.status, r.ok, r.json(), r.headers["content-type"]
api.post("objects", data={"name": "x"})        # JSON body
api.put(...); api.patch(...); api.delete("objects/ID")
api.dispose()
page.request.post(...)                          # shares the browser's cookies

Lessons: 54, 55.


🐞 Debug, Trace, Report

⌨️ Terminal

pytest -k coupon --headed --slowmo 500
$env:PWDEBUG = "1"; pytest -k coupon          # Inspector (PowerShell); bash: PWDEBUG=1 pytest -k coupon
pytest --lf -x --pdb
$env:DEBUG = "pw:api"; pytest -k coupon -s     # log every API call
pytest --tracing retain-on-failure
playwright show-trace test-results/<test>/trace.zip
python -m playwright trace open test-results/<test>/trace.zip
python -m playwright cli open https://sqatools.in/ --browser firefox
page.pause()                                    # Inspector at this line (headed)
context.tracing.start(screenshots=True, snapshots=True, sources=True)
context.tracing.stop(path="trace.zip")

Lessons: 61, 62, 63, 64, 70.


Advertisement

🚀 CI (GitHub Actions)

- uses: actions/checkout@v7
- uses: actions/setup-python@v7
  with: { python-version: "3.13", cache: pip }
- run: pip install -r requirements.txt
- run: playwright install --with-deps chromium
- run: pytest -n auto --tracing retain-on-failure --junitxml=reports/junit.xml
- uses: actions/upload-artifact@v7
  if: failure()
  with: { name: test-results, path: test-results/ }

Docker image: mcr.microsoft.com/playwright/python:v1.65.2-noble (match your Playwright version). Lessons: 66, 67, 68.


🧪 One Test That Uses Most of It

📄 pytest.ini

[pytest]
addopts = --base-url https://sqatools.in

📄 tests/test_cheat_sheet.py

import re

import pytest
from playwright.sync_api import Page, expect

SHOP = "/dummy-ecommerce-website/"


@pytest.mark.parametrize("code, discount", [("SAVE10", "−₹500"), ("FLAT200", "−₹200")], ids=["save10", "flat200"])
def test_coupon_flow(page: Page, code, discount):
    page.goto(SHOP + "#/login")                                            # relative URL
    page.get_by_test_id("login-username").fill("testuser")                 # test-id locator
    page.get_by_test_id("login-password").fill("Test@123")
    page.get_by_role("button", name="Log in", exact=True).click()          # role locator, exact name
    expect(page.get_by_test_id("account-button")).to_contain_text("Hi, Test")

    page.get_by_test_id("search-input").fill("earbuds")
    page.get_by_test_id("search-button").click()
    card = page.get_by_test_id("product-card").filter(has_text="Wireless Earbuds")
    card.get_by_role("button", name="Add to cart").click()                 # chained, filtered locator
    expect(page.get_by_test_id("cart-count")).to_have_text("1")

    page.get_by_test_id("cart-link").click()
    expect(page).to_have_url(re.compile(r"#/cart$"))
    page.get_by_test_id("coupon-input").fill(code)
    page.get_by_test_id("apply-coupon").click()
    expect(page.get_by_test_id("coupon-message")).to_have_text(f"Coupon {code} applied.")
    expect(page.get_by_test_id("coupon-discount")).to_have_text(discount)

⌨️ Terminal

pytest -v --tracing retain-on-failure

🖥️ Output

============================= test session starts =============================
platform win32 -- Python 3.15.1, pytest-9.2.0, pluggy-1.7.0 -- C:\Users\you\playwright-python\.venv\Scripts\python.exe
cachedir: .pytest_cache
baseurl: https://sqatools.in
rootdir: C:\Users\you\playwright-python
configfile: pytest.ini
plugins: allure-pytest-2.16.2, base-url-2.1.0, bdd-9.0.1, html-4.2.0, metadata-3.1.1, playwright-0.10.0, rerunfailures-16.7, xdist-3.8.0
collecting ... collected 2 items

tests/test_cheat_sheet.py::test_coupon_flow[chromium-save10] PASSED      [ 50%]
tests/test_cheat_sheet.py::test_coupon_flow[chromium-flat200] PASSED     [100%]

============================== 2 passed in 6.54s ==============================

Advertisement

🏋️ Practice Exercises

Try each exercise on your own first, then open the answer to compare. The answers use the same practice sites and project layout as the lesson.

Exercise 1: Without looking above, write the locator for the “Add to cart” button inside the product card that contains “Wireless Earbuds”.

Show answer
page.get_by_test_id("product-card").filter(has_text="Wireless Earbuds").get_by_role("button", name="Add to cart")

Exercise 2: Write the one-line command that runs the smoke tests in Firefox and WebKit in parallel and keeps traces only for failures.

Show answer
pytest -m smoke --browser firefox --browser webkit -n auto --tracing retain-on-failure

Exercise 3: Which three lines make every test in a folder start logged in from .auth/user.json?

Show answer
@pytest.fixture(scope="session")
def browser_context_args(browser_context_args):
    return {**browser_context_args, "storage_state": ".auth/user.json"}

Put it in that folder’s conftest.py (and create the file in a session fixture or a setup script first).

Exercise 4: Mock **/api/products* with an empty list and assert the page shows “0 products”.

Show answer
page.route("**/api/products*", lambda r: r.fulfill(json={"data": [], "meta": {"total": 0}}))
page.goto("/shop")
expect(page.get_by_test_id("status")).to_have_text("0 products")

🧠 MCQ Quiz: Playwright Python Cheat Sheet

10 questions on this lesson. Pick one answer for each, then press Check answers to see your score and an explanation for every question.

  1. Which command opens Codegen for a URL?
  2. Which option keeps a screenshot only for failed tests?
  3. What does exact=True change in get_by_role(..., name="Log in", exact=True)?
  4. How do you assert three list items in order?
  5. Which call starts every new context logged in?
  6. How do you fail a network request on purpose?
  7. Which client sends API requests without a browser?
  8. How do you open a trace from the terminal as text?
  9. Which Docker image tag matches Playwright 1.65.2?
  10. Which plugin adds --reruns?

Want a longer, timed test? Take the Playwright Python mock interviews (13 modules, 20 MCQs each).


Advertisement

❓ Frequently Asked Questions

🤔 Can I download this cheat sheet as a PDF?

Use your browser’s Print → Save as PDF on this page; the code blocks and tables print cleanly.

🤔 Is there a cheat sheet for Playwright with TypeScript?

Yes, the Playwright TypeScript cheat sheet covers the same ground for Playwright Test.

🤔 Which versions does this cheat sheet use?

Playwright for Python 1.65, pytest-playwright 0.10, pytest 9 and Python 3.10 or newer. The API is stable across recent versions; check the release notes when upgrading.

🤔 Where do I practise these commands?

On the SQA Tools practice apps (shop, bank, booking), the practice API and the automation practice page, all used throughout this course.

🤔 What should I learn after this course?

Build one of the Module 14 projects end to end in your own repository, add CI, and then explore the AI-assisted workflows in Module 13 with your team’s application.


🏁 Summary

  • Install with pytest-playwright and playwright install; configure base URL and markers in pytest.ini.
  • Prefer role, label and test-id locators; chain and filter; assert with retrying expect.
  • Use fixtures for context options, devices and logged-in state; routes and HAR for the network; APIRequestContext for APIs.
  • Debug with headed runs, PWDEBUG, traces and the trace CLI; report with pytest-html, Allure and JUnit.
  • Run in parallel with xdist and in CI with pinned versions and failure artifacts.

🎬 Watch the Playwright tutorial series on YouTube!

Subscribe to SqaToolsByDY • Practice on the SQA Tools Automation Practice Page