Visual Regression Testing in Playwright Python (Screenshot Comparison)

Functional assertions check text, values and states, but they cannot see that a button turned the wrong colour or a layout broke. Visual regression testing compares screenshots with approved baseline images and fails when pixels change. Playwright for TypeScript has this built in; Playwright for Python does not, so in this lesson you will build your own screenshot comparison fixture with Pillow and pixelmatch, try a ready-made pytest plugin, and use the built-in ARIA snapshot assertion to check page structure.

📖 What You’ll Learn: how visual regression testing works (baseline, comparison, diff), why Playwright for Python has no to_have_screenshot, building an assert_snapshot fixture with Pillow and pixelmatch, threshold and allowed-difference settings, first-run baselines and an –update-snapshots option, reading the diff image, masking and other stability techniques, the pytest-playwright-visual-snapshot plugin, cloud visual testing services, and structural snapshots with to_match_aria_snapshot.


👁️ What Is Visual Regression Testing?

Imagine a CSS change that makes the “Submit” button white on a white background. Every functional test still passes: the button exists, it is enabled, its text is “Submit” and clicking it works. A user, however, cannot see it.

Visual regression testing catches this kind of bug by comparing pictures:

  1. Baseline: the first time, the test takes a screenshot and saves it as the approved image.
  2. Comparison: on later runs, it takes a new screenshot and compares it pixel by pixel with the baseline.
  3. Diff: if too many pixels differ, the test fails and saves the new image and a diff image that highlights the changes.
  4. Review: a person looks at the diff. If the change is a bug, fix the app. If it is intended (a redesign), update the baseline.

Python has no built-in to_have_screenshot

In Playwright for TypeScript, the test runner provides expect(page).toHaveScreenshot(). In Playwright for Python 1.64, there is no to_have_screenshot() assertion: expect() for pages and locators has no screenshot comparison. You have three options:

OptionGood for
Your own fixture with Pillow + pixelmatchFull control, no extra plugin, a great way to learn how it works
A pytest plugin such as pytest-playwright-visual-snapshotReady-made baseline handling and options
A cloud service (Percy, Applitools)Teams that want a web dashboard for reviewing changes

This lesson covers the first two in detail. You will also meet to_match_aria_snapshot(), a built-in Python assertion that compares the structure of the page instead of its pixels.


🧰 Building an assert_snapshot Fixture

Install the two libraries the fixture uses:

⌨️ Terminal

pip install pillow pixelmatch
  • Pillow (PIL) opens, compares and saves images.
  • pixelmatch is a Python port of the pixel comparison library used by many visual testing tools. It counts the differing pixels, ignores anti-aliasing differences at text edges, and draws a diff image.

Put the fixture in the project’s root conftest.py, so every test can use it:

📄 conftest.py

import io
import sys
from pathlib import Path

import pytest
from PIL import Image
from pixelmatch.contrib.PIL import pixelmatch

SNAPSHOT_DIR = Path("__snapshots__")          # approved baselines (commit these to Git)
RESULTS_DIR = Path("snapshot-results")        # actual and diff images of failures


def pytest_addoption(parser):
    parser.addoption(
        "--update-snapshots",
        action="store_true",
        help="Save the current screenshots as the new baselines",
    )


@pytest.fixture
def assert_snapshot(request, browser_name):
    update = request.config.getoption("--update-snapshots")

    def check(image: bytes, name: str, threshold: float = 0.1, max_diff_ratio: float = 0.0):
        __tracebackhide__ = True                # report failures at the test's line, not in here

        # One baseline per browser and operating system: rendering differs between them
        file_name = f"{name}-{browser_name}-{sys.platform}.png"
        baseline = SNAPSHOT_DIR / file_name

        # First run, or an explicit update: save the baseline
        if update or not baseline.exists():
            baseline.parent.mkdir(parents=True, exist_ok=True)
            baseline.write_bytes(image)
            if not update:
                pytest.fail(f"No baseline yet. Saved {baseline.as_posix()}: review it, then run again.")
            return

        actual = Image.open(io.BytesIO(image))
        expected = Image.open(baseline)
        if actual.size != expected.size:
            pytest.fail(f"Size changed: baseline {expected.size}, now {actual.size}")

        # Compare: returns the number of pixels that differ and draws the diff image
        diff = Image.new("RGBA", actual.size)
        different = pixelmatch(actual, expected, diff, threshold=threshold)
        ratio = different / (actual.width * actual.height)

        if ratio > max_diff_ratio:
            out = RESULTS_DIR / name
            out.mkdir(parents=True, exist_ok=True)
            actual.save(out / f"actual-{file_name}")
            expected.save(out / f"expected-{file_name}")
            diff.save(out / f"diff-{file_name}")
            pytest.fail(
                f"{different} pixels ({ratio:.2%}) differ from {baseline.as_posix()}. "
                f"See {out.as_posix()}/"
            )

    return check

Line by line:

  • pytest_addoption() adds a --update-snapshots command-line flag (you learned this hook in Module 3).
  • The fixture returns the inner function check(), so a test calls assert_snapshot(image_bytes, "name").
  • __tracebackhide__ = True is a pytest feature: it hides this helper from failure tracebacks, so the report points at the line in your test.
  • browser_name is a pytest-playwright fixture (“chromium”, “firefox” or “webkit”). Together with sys.platform (“win32”, “linux”, “darwin”) it makes the file name unique, because fonts and anti-aliasing render differently on each browser and operating system.
  • First run: there is no baseline, so the image is saved and the test fails on purpose. A missing baseline must never pass silently; a person should look at it first.
  • Size check: pixelmatch needs two images of the same size. A size change usually means the layout changed, so report it clearly.
  • pixelmatch(actual, expected, diff, threshold=0.1) compares colour by colour. threshold (0 to 1) is how different a pixel’s colour must be to count as changed: smaller is stricter.
  • max_diff_ratio is how many pixels may differ (0.0 = none, 0.01 = 1%). Raise it a little if tiny rendering noise makes a test flaky.
  • On failure, the expected, actual and diff images are saved side by side for review.

✅ A First Visual Test

The test takes a screenshot of the web table on the practice page and compares it with the baseline:

📄 tests/test_visual.py

import pytest
from playwright.sync_api import Page


@pytest.fixture
def practice(page: Page) -> Page:
    page.goto("https://sqatools.in/automation-practice-page/")
    return page


def test_web_table_looks_right(practice: Page, assert_snapshot):
    table = practice.locator("table")
    assert_snapshot(table.screenshot(animations="disabled"), "web-table")
  • An element screenshot is much more stable than a full page: the practice page also contains ads and comments that change, but the table does not.
  • animations="disabled" stops CSS animations and transitions, so a moving element cannot cause a difference.

Run 1: no baseline yet.

⌨️ Terminal

pytest -q tests

🖥️ Output

F                                                                        [100%]
================================== FAILURES ===================================
____________________ test_web_table_looks_right[chromium] _____________________

practice = <Page url='https://sqatools.in/automation-practice-page/'>
assert_snapshot = <function assert_snapshot.<locals>.check at 0x00000218205DD380>

    def test_web_table_looks_right(practice: Page, assert_snapshot):
        table = practice.locator("table")
>       assert_snapshot(table.screenshot(animations="disabled"), "web-table")
E       Failed: No baseline yet. Saved __snapshots__/web-table-chromium-win32.png: review it, then run again.

tests\test_visual.py:13: Failed
=========================== short test summary info ===========================
FAILED tests/test_visual.py::test_web_table_looks_right[chromium] - Failed: N...
1 failed, 1 warning in 2.91s

Open __snapshots__/web-table-chromium-win32.png, check that it looks right, and commit it to Git.

Run 2: the comparison passes.

⌨️ Terminal

pytest -q tests

🖥️ Output

.                                                                        [100%]
1 passed, 1 warning in 2.73s

🔴 Catching a Visual Bug

Now simulate a developer’s CSS change that turns the table headers red. page.add_style_tag() injects a stylesheet into the page, just like a new CSS rule in the application would:

📄 demos/test_regression.py

import pytest
from playwright.sync_api import Page


@pytest.fixture
def practice(page: Page) -> Page:
    page.goto("https://sqatools.in/automation-practice-page/")
    return page


def test_table_after_css_change(practice: Page, assert_snapshot):
    practice.add_style_tag(content="th { color: red; }")      # the "bug"
    table = practice.locator("table")
    assert_snapshot(table.screenshot(animations="disabled"), "web-table")

⌨️ Terminal

pytest -q demos

🖥️ Output

F                                                                        [100%]
================================== FAILURES ===================================
____________________ test_table_after_css_change[chromium] ____________________

practice = <Page url='https://sqatools.in/automation-practice-page/'>
assert_snapshot = <function assert_snapshot.<locals>.check at 0x00000263C481D640>

    def test_table_after_css_change(practice: Page, assert_snapshot):
        practice.add_style_tag(content="th { color: red; }")      # the "bug"
        table = practice.locator("table")
>       assert_snapshot(table.screenshot(animations="disabled"), "web-table")
E       Failed: 412 pixels (0.32%) differ from __snapshots__/web-table-chromium-win32.png. See snapshot-results/web-table/

demos\test_regression.py:14: Failed
=========================== short test summary info ===========================
FAILED demos/test_regression.py::test_table_after_css_change[chromium] - Fail...
1 failed, 1 warning in 2.77s

Every functional check on this table would still pass: the same headers, the same cells, the same text. Only the visual comparison noticed. The files involved:

🖥️ Output

__snapshots__/web-table-chromium-win32.png
snapshot-results/web-table/actual-web-table-chromium-win32.png
snapshot-results/web-table/diff-web-table-chromium-win32.png
snapshot-results/web-table/expected-web-table-chromium-win32.png
  • expected-...png is the baseline, actual-...png the new screenshot.
  • diff-...png shows the unchanged pixels faded and the changed pixels in red. In this run, only the three header words (ID, Name, Role) were red, so you see at a glance that only the header row changed. Yellow pixels at the letter edges are anti-aliasing differences that pixelmatch detected and did not count.

Accepting an intended change

When a change is intended, update the baselines and commit them:

⌨️ Terminal

pytest -q tests --update-snapshots

🖥️ Output

.                                                                        [100%]
1 passed, 1 warning in 2.46s

⚠️ Watch out: Never run --update-snapshots just to make a red build green. Look at every diff first; updating a baseline means “this is now correct”.


🎯 Making Visual Tests Stable

Visual tests fail on any pixel change, including ones that are not bugs. These techniques keep them reliable:

ProblemSolution
Dates, times, ads, avatars, random datamask=[locator, ...] in screenshot(), or style= to hide them
Animations, transitions, blinking cursoranimations="disabled"; caret="hide" is the default
Different fonts on Windows, macOS and LinuxSeparate baselines per OS (as in the fixture), or always run visual tests in the same Docker image
Different window sizesKeep the viewport fixed (pytest-playwright uses 1280 x 720)
Content still loadingWait first, for example expect(locator).to_be_visible(), before the screenshot
Large pages with many moving partsScreenshot components (a header, a card, a form) instead of the full page
Tiny rendering noiseA small max_diff_ratio, such as 0.001, or a higher threshold

For example, to mask the changing parts of a page:

image = page.screenshot(
    full_page=True,
    animations="disabled",
    mask=[page.locator(".ad-banner"), page.get_by_test_id("current-time")],
)
assert_snapshot(image, "home-page")

💡 Tip: Generate and compare baselines in one environment, usually CI. A baseline created on a Windows laptop will not match a screenshot taken on a Linux CI server, because the fonts are different.


🔌 Option 2: The pytest-playwright-visual-snapshot Plugin

If you would rather not maintain your own fixture, the pytest-playwright-visual-snapshot plugin (version 0.5.1, which needs Python 3.11 or newer) provides an assert_snapshot fixture built on the same libraries:

⌨️ Terminal

pip install pytest-playwright-visual-snapshot

📄 plugin/pytest.ini

[pytest]

📄 plugin/test_plugin_visual.py

from playwright.sync_api import Page


def test_table_with_plugin(page: Page, assert_snapshot):
    page.goto("https://sqatools.in/automation-practice-page/")
    assert_snapshot(page.locator("table"))
  • Pass a page or a locator; the plugin takes the screenshot itself, with animations disabled.
  • It also accepts threshold=, name= and mask_elements= (a list of CSS selectors).
  • Command-line options: --update-snapshots, --ignore-size-diff and --disable-visual-snapshots. Settings such as the snapshot folder and default masks can go in pytest.ini.
  • The empty pytest.ini here only makes this folder its own pytest project for the demo. In a real project, use either your own fixture or the plugin: both define --update-snapshots and assert_snapshot, so they cannot be loaded together.

The first run creates the baseline and fails; the second run compares (... marks lines removed from the long traceback):

🖥️ Output

# First run
2026-11-01T10:35:09.415283Z [info     ] structlog output capture disabled, no output directory specified [structlog_config.pytest]
.E                                                                       [100%]
=================================== ERRORS ====================================
____________ ERROR at teardown of test_table_with_plugin[chromium] ____________
...
E           Failed: [playwright-visual-snapshot] New snapshot(s) created. Please review images. C:\pwv\playwright-python-visual-testing\plugin\__snapshots__\test_plugin_visual\test_table_with_plugin\test_table_with_plugin[chromium][win32].png
...
================================= slow tests ==================================
[slow] 2.53s test_plugin_visual.py::test_table_with_plugin[chromium]
=========================== short test summary info ===========================
ERROR test_plugin_visual.py::test_table_with_plugin[chromium] - Failed: [play...
1 passed, 1 warning, 1 error in 3.09s

# Second run
.                                                                        [100%]
================================= slow tests ==================================
[slow] 2.44s test_plugin_visual.py::test_table_with_plugin[chromium]
1 passed, 1 warning in 2.97s

The baseline file it created:

🖥️ Output

plugin/__snapshots__/test_plugin_visual/test_table_with_plugin/test_table_with_plugin[chromium][win32].png

What to notice in this real output:

  • The plugin reports a new baseline or a mismatch at the end of the test, from a fixture finalizer. pytest therefore shows the test as passed plus an error at teardown, and the run still fails.
  • The structlog log line and the “slow tests” section come from structlog-config, a dependency the plugin installs, which registers its own pytest plugin.
  • Baselines go to __snapshots__/<test file>/<test name>/<test name>[browser][os].png, so they are already separated per browser and operating system.

📝 Note: On GitHub Actions (version 0.5.1 checks for the GITHUB_ACTIONS environment variable), this plugin also overwrites the baseline file in place after a mismatch, so you can download the new images from the CI artifacts. The test still fails.

Cloud visual testing services

Percy (BrowserStack) and Applitools Eyes publish Python SDKs for Playwright on PyPI (percy-playwright and eyes-playwright). They upload screenshots to a web dashboard where the team reviews and approves changes, and Applitools markets its comparison as “Visual AI” that ignores insignificant differences. Both are commercial services (check their current pricing); consider them when many people need to review visual changes.


🌳 Structural Snapshots: to_match_aria_snapshot

Pixel comparison catches visual changes. Sometimes you want something more robust: did the structure of a component change? Playwright for Python has a built-in assertion for this. to_match_aria_snapshot() compares the element’s accessibility tree, described in YAML:

📄 aria/test_aria.py

from playwright.sync_api import Page, expect


def test_table_structure(page: Page):
    page.goto("https://sqatools.in/automation-practice-page/")
    expect(page.locator("table")).to_match_aria_snapshot("""
      - table:
        - rowgroup:
          - row "ID Name Role"
        - rowgroup:
          - row "1 Deepesh Trainer"
          - row "2 Rahul Tester"
          - row "3 Anita Developer"
    """)


def test_partial_and_regex(page: Page):
    page.goto("https://sqatools.in/automation-practice-page/")
    # Only list what matters: other options and attributes may exist
    expect(page.locator("#country")).to_match_aria_snapshot("""
      - combobox:
        - option "India"
        - option /U.*/
    """)


def test_print_a_snapshot(page: Page):
    page.goto("https://sqatools.in/automation-practice-page/")
    print("\n" + page.locator("#country").aria_snapshot())

⌨️ Terminal

pytest -q -s aria

🖥️ Output

..
- combobox:
  - option "–Select Country–" [selected]
  - option "India"
  - option "USA"
  - option "UK"
  - option "Australia"
.
3 passed, 1 warning in 6.62s
  • Each line is - role "accessible name", indented to show nesting.
  • The template matches partially: you can leave out children, such as the rows’ cells and the other countries above. The children you list must appear in that order.
  • /U.*/ is a regular expression for the name; here it matched “USA”.
  • locator.aria_snapshot() returns the snapshot as text. Print it once, check it, and paste it into your test.
  • ARIA snapshots ignore colours and layout, so they do not replace pixel comparison. They are excellent for menus, tables and forms whose content and structure must not change, and they do not depend on the operating system’s fonts.

🏋️ 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: Describe the three steps of a visual regression check in your own words.

Show answer

(1) Baseline: the first run saves a reference screenshot after a human approves it. (2) Comparison: later runs take a new screenshot of the same page state and compare it pixel by pixel with the baseline. (3) Diff: if the difference is above the threshold, the test fails and saves a diff image highlighting the changed pixels for review.

Exercise 2: A visual test fails every morning because the page shows the current date. Give two fixes.

Show answer

Mask the date element in the screenshot (mask=[page.locator("#today")]), or freeze time in the browser with page.clock.set_fixed_time(...) before loading the page so the date never changes.

Exercise 3: Your visual baselines were created on Windows and the CI runs on Linux; every test fails with small font differences. What do you do?

Show answer

Create and compare baselines on the same platform and browser as CI, ideally inside the Playwright Docker image, and store baselines per platform/browser. Font rendering differs between operating systems, so cross-platform pixel comparison is unreliable.


🧠 MCQ Quiz: Visual Regression Testing in Python

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. What is a baseline in visual testing?
  2. Does Playwright for Python include to_have_screenshot()?
  3. What does a pixel-diff threshold control?
  4. Which technique makes visual tests more stable?
  5. What should happen on the first run when no baseline exists?
  6. What is an --update-snapshots option for?
  7. Why should baselines be stored per browser?
  8. What does a diff image show?
  9. Which library pair can implement pixel comparison in Python?
  10. When are cloud visual testing services useful?

Want a longer, timed test? Take the Module 5 mock interview (20 MCQs in 20 minutes).


❓ Frequently Asked Questions

🤔 Does Playwright Python have toHaveScreenshot?

No. to_have_screenshot() exists only in the TypeScript/JavaScript test runner. In Python, compare screenshots with your own fixture (Pillow and pixelmatch), a pytest plugin, or a cloud service.

🤔 Where should I store baseline images?

In your Git repository, next to the tests, so a baseline change is reviewed in the same pull request as the code change that caused it.

🤔 Why does my visual test fail on CI but pass locally?

Usually different fonts or rendering on another operating system. Create the baselines in the same environment that compares them, typically a fixed Docker image in CI, and keep one baseline per browser and OS.

🤔 What threshold should I use?

Start with pixelmatch’s default threshold=0.1 and max_diff_ratio=0 (no differing pixels). Raise them only if you see real noise, and only as much as needed; a high tolerance hides real bugs.

🤔 Can I compare a full page?

Yes, with page.screenshot(full_page=True), but full pages contain more changing content. Mask dynamic parts, or prefer component screenshots for stable tests.


🏁 Summary

  • Visual regression testing compares screenshots with approved baselines and shows the differences in a diff image.
  • Playwright for Python has no to_have_screenshot(); build an assert_snapshot fixture with Pillow and pixelmatch, or use a plugin such as pytest-playwright-visual-snapshot.
  • A missing baseline should fail; --update-snapshots accepts intended changes after review.
  • Keep visual tests stable: element screenshots, masks, disabled animations, a fixed viewport, and one environment for baselines.
  • to_match_aria_snapshot() is the built-in way to check a component’s structure, independent of fonts and colours.

You have finished Module 5. Test yourself with the Module 5 mock interview, then continue to Module 6, where you will master Playwright’s pytest fixtures: browser, context and page scopes, and your own fixtures.

🎬 Watch the Playwright tutorial series on YouTube!

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

Screenshots, Videos and Traces in Playwright Python (on Failure)

When a test fails on a CI server at 2 a.m., the error message alone rarely tells you why. Screenshots, videos and traces are your evidence: they show what the browser looked like and what happened step by step. In this lesson you will take every kind of screenshot from code, switch on automatic screenshots, videos and traces for failed tests with pytest-playwright, find the files it creates, attach them to an HTML report and open a trace in the Trace Viewer.

📖 What You’ll Learn: page.screenshot for the viewport and the full page, element screenshots, clip, mask, style and JPEG options, screenshots as bytes, the –screenshot, –video, –tracing and –full-page-screenshot options with on, off and only-on-failure or retain-on-failure, the –output folder and its file names, setting the options in pytest.ini, artifacts in pytest-html reports, recording video and traces from code, trace groups, and reading a trace in the Trace Viewer.


📸 Why Capture Evidence?

A failing test tells you that something is wrong. Evidence tells you what was on the screen:

ArtifactWhat it showsCost
ScreenshotOne picture of the page at a momentSmall, fast
VideoThe whole test as a movieLarger files, slight slowdown
TraceEvery action with DOM snapshots, network calls, console logs and source codeThe most detail, larger files

The usual setup: keep all three only for failed tests. Passing tests then cost almost nothing, and every failure comes with everything you need to debug it.


🖼️ Screenshots from Code

All screenshot examples use the SQA Tools practice page:

📄 tests/conftest.py

import pytest
from playwright.sync_api import Page


@pytest.fixture
def practice(page: Page) -> Page:
    page.goto("https://sqatools.in/automation-practice-page/")
    return page

A small helper reads a PNG file’s width and height (they are stored at bytes 16 to 24 of every PNG), so each test can print what it captured:

📄 tests/images.py

import struct


def png_size(data: bytes) -> tuple[int, int]:
    """Return (width, height) of PNG image bytes."""
    return struct.unpack(">II", data[16:24])

📄 tests/test_screenshots.py

from pathlib import Path

from images import png_size
from playwright.sync_api import Page

OUT = Path("screenshots")


def test_page_screenshots(practice: Page):
    # 1. The visible part of the page (the viewport)
    viewport = practice.screenshot(path=OUT / "viewport.png")

    # 2. The whole scrollable page
    full = practice.screenshot(path=OUT / "full-page.png", full_page=True)

    # 3. A rectangle of the page, in CSS pixels from the top-left corner
    corner = practice.screenshot(path=OUT / "corner.png", clip={"x": 0, "y": 0, "width": 400, "height": 300})

    print("\nviewport :", png_size(viewport))
    print("full page:", png_size(full))
    print("clip     :", png_size(corner))
  • page.screenshot() captures the viewport by default. pytest-playwright’s default viewport is 1280 x 720.
  • full_page=True scrolls through the page and captures all of it. The height depends on the page content.
  • clip= captures one rectangle of the page.
  • path= saves the file; Playwright creates missing folders. The method also returns the image as bytes, whether you save it or not.

Element screenshots, masks and styles

📄 tests/test_screenshots.py

def test_element_and_masked_screenshots(practice: Page):
    # 4. One element only: the web table
    table = practice.locator("table").screenshot(path=OUT / "table.png")
    print("\ntable    :", png_size(table))

    # 5. Hide sensitive or changing parts with a solid box
    practice.locator("#username").fill("secret_user")
    practice.screenshot(
        path=OUT / "masked.png",
        mask=[practice.locator("#username"), practice.locator("#password")],
        mask_color="#FF00FF",            # default is pink #FF00FF
    )

    # 6. Inject CSS only for the screenshot, for example to hide a banner
    practice.screenshot(path=OUT / "styled.png", style="#username { visibility: hidden; }")

    # 7. JPEG with a quality setting: smaller files for long-term storage
    practice.screenshot(path=OUT / "viewport.jpg", type="jpeg", quality=60)

    for name in ["viewport.png", "viewport.jpg"]:
        print(f"{name:<12}: {(OUT / name).stat().st_size:,} bytes")
  • locator.screenshot() captures just that element, after scrolling it into view. It waits until the element is visible and stable.
  • mask= takes a list of locators and paints a box over each one. Use it for passwords, timestamps, ads or anything that changes from run to run.
  • style= injects a stylesheet only while the screenshot is taken; the page itself is not changed.
  • type="jpeg" with quality= (0 to 100) gives smaller files: here about half the size of the PNG (the exact JPEG size changes slightly between runs because the live page has ads). PNG is lossless and the default.
  • The file type follows the extension of path (.png, .jpg or .webp), or set it with type=.
  • Two more useful options: animations="disabled" stops CSS animations and transitions, and omit_background=True gives a transparent background (not for JPEG).

⌨️ Terminal

pytest -q -s tests/test_screenshots.py

🖥️ Output

viewport : (1280, 720)
full page: (1280, 8894)
clip     : (400, 300)
.
table    : (740, 172)
viewport.png: 61,548 bytes
viewport.jpg: 29,672 bytes
.
2 passed, 1 warning in 4.78s

💡 Tip: You can attach page.screenshot() bytes to a report without writing a file. In the reporting module you will attach them to Allure reports.


🤖 Automatic Artifacts with pytest-playwright

You do not have to call screenshot() in every test. pytest-playwright has command-line options that capture evidence for you after each test:

OptionValuesDefault
--screenshoton, off, only-on-failureoff
--full-page-screenshotflag: makes those screenshots full pageoff
--videoon, off, retain-on-failureoff
--tracingon, off, retain-on-failureoff
--outputfolder for all artifactstest-results
  • only-on-failure and retain-on-failure record during every test but keep the files only when the test fails.
  • The screenshot is taken at the end of the test, when the browser context closes, so it shows the page as it was when the test failed.

Here are two tests, one passing and one failing:

📄 demos/test_checkout.py

from playwright.sync_api import Page, expect


def test_page_opens(page: Page):
    page.goto("https://sqatools.in/automation-practice-page/")
    expect(page).to_have_title("Automation Practice Page - SQA Tools")


def test_wrong_heading(page: Page):
    page.goto("https://sqatools.in/automation-practice-page/")
    expect(page.locator("h1").first).to_have_text("Checkout", timeout=2_000)

Run them with all three artifact types kept on failure:

⌨️ Terminal

pytest -q demos --screenshot only-on-failure --video retain-on-failure --tracing retain-on-failure

🖥️ Output

.F                                                                       [100%]
================================== FAILURES ===================================
________________________ test_wrong_heading[chromium] _________________________

page = <Page url='https://sqatools.in/automation-practice-page/'>

    def test_wrong_heading(page: Page):
        page.goto("https://sqatools.in/automation-practice-page/")
>       expect(page.locator("h1").first).to_have_text("Checkout", timeout=2_000)
E       AssertionError: Locator expected to have text 'Checkout'
E       Actual value: Automation Practice Page 
E       Call log:
E         - Expect "to_have_text" locator("h1").first with timeout 2000ms
E         - waiting for locator("h1").first
E           20 × locator resolved to <h1 class="entry-title" itemprop="headline">Automation Practice Page</h1>
E              - unexpected value "Automation Practice Page"
E       
E       Aria snapshot:
E       - heading "Automation Practice Page" [level=1]

demos\test_checkout.py:11: AssertionError
=========================== short test summary info ===========================
FAILED demos/test_checkout.py::test_wrong_heading[chromium] - AssertionError:...
1 failed, 1 passed, 1 warning in 6.91s

After the run, the test-results folder contains:

🖥️ Output

test-results/demos-test-checkout-py-test-wrong-heading-chromium/test-failed-1.png
test-results/demos-test-checkout-py-test-wrong-heading-chromium/trace.zip
test-results/demos-test-checkout-py-test-wrong-heading-chromium/video.webm
  • There is one folder per test, named after the test’s node id (file, test name and browser). Only the failed test has a folder.
  • test-failed-1.png is the screenshot. With several pages in a test, you get test-failed-1.png, test-failed-2.png and so on; with --screenshot on, a passing test’s file is called test-finished-1.png.
  • video.webm is the video (WebM format, which every modern browser can play).
  • trace.zip is the trace, which you will open in a moment.
  • pytest-playwright empties the output folder at the start of each run, so old results do not mix with new ones. Copy anything you want to keep.

📝 Note: With pytest-rerunfailures, a retried test’s artifacts go into a separate folder ending in -retry1, -retry2 and so on, so the first failure is not overwritten.

Setting the options once in pytest.ini

Typing the options every time is tedious. Put them in addopts:

📄 configured/pytest.ini

[pytest]
addopts =
    --screenshot only-on-failure
    --video retain-on-failure
    --tracing retain-on-failure

📄 configured/test_login.py

from playwright.sync_api import Page, expect


def test_login_button(page: Page):
    page.goto("https://sqatools.in/login-page/")
    expect(page.get_by_role("button", name="Log in")).to_have_text("Sign in", timeout=2_000)

⌨️ Terminal

cd configured
pytest -q

🖥️ Output

F                                                                        [100%]
================================== FAILURES ===================================
_________________________ test_login_button[chromium] _________________________

page = <Page url='https://sqatools.in/login-page/'>

    def test_login_button(page: Page):
        page.goto("https://sqatools.in/login-page/")
>       expect(page.get_by_role("button", name="Log in")).to_have_text("Sign in", timeout=2_000)
E       AssertionError: Locator expected to have text 'Sign in'
E       Actual value: 
E                           Log in
E                        
E       Call log:
E         - Expect "to_have_text" get_by_role("button", name="Log in") with timeout 2000ms
E         - waiting for get_by_role("button", name="Log in")
E           20 × locator resolved to <button type="submit" id="loginbutton" class="btn-login">↵                    Log in↵                </button>
E              - unexpected value "
E                           Log in
E                       "
E       
E       Aria snapshot:
E       - button "Log in"

test_login.py:6: AssertionError
=========================== short test summary info ===========================
FAILED test_login.py::test_login_button[chromium] - AssertionError: Locator e...
1 failed, 1 warning in 5.28s

The button on that page says “Log in”, not “Sign in”, so the test fails and the artifacts appear without any option on the command line.

💡 Tip: A common pattern is retain-on-failure locally and in CI, and on only when you are investigating a specific problem. Videos and traces of every test can fill a CI disk quickly.


📊 Artifacts in a pytest-html Report

If pytest-html is installed and you pass --html, pytest-playwright 0.10 adds the kept artifacts to the report automatically: the screenshot is shown inline, the video can be played, and the trace is a link.

⌨️ Terminal

pip install pytest-html
pytest -q demos --screenshot only-on-failure --output report-results --html report/index.html

A small script confirms the screenshot is linked in the report:

🖥️ Output

report size: 28,902 characters
mentions 'Screenshot': True
links: ['report-results/demos-test-checkout-py-test-wrong-heading-chromium/test-failed-1.png']
  • The report links to the files in the output folder. Keep the report and the output folder together when you publish them as CI artifacts.
  • Add --self-contained-html to embed screenshots and videos inside the HTML file itself (traces are always linked).
  • pytest-playwright also records each artifact’s path on the test report (as playwright_screenshot, playwright_video and playwright_trace properties), so JUnit XML reports list them too.

🎬 Recording Video from Code

Outside pytest-playwright, or when you need different settings for one test, create a context with record_video_dir:

📄 tests/test_video_manual.py

from pathlib import Path

from playwright.sync_api import Browser


def test_record_video(browser: Browser):
    context = browser.new_context(
        record_video_dir="videos/",
        record_video_size={"width": 1280, "height": 720},
    )
    page = context.new_page()
    page.goto("https://sqatools.in/automation-practice-page/")
    page.locator("#username").fill("video_user")

    context.close()                         # the video file is finished when the context closes

    video = Path(page.video.path())
    print(f"\nvideo: {video.parent.name}/<random name>{video.suffix}, {video.stat().st_size > 0 = }")
  • record_video_dir switches recording on for every page in the context.
  • record_video_size sets the video resolution. Without it, the video is the viewport scaled down to fit 800 x 800 (1280 x 720 becomes 800 x 450).
  • The video is **complete only after context.close()**. Read page.video.path() after closing, or use page.video.save_as("my-name.webm") to choose a file name.
  • The browser fixture comes from pytest-playwright; a context you create yourself is yours to close.

🧵 Traces from Code and Trace Groups

📄 tests/test_trace_manual.py

import zipfile
from pathlib import Path

from playwright.sync_api import Browser


def test_record_trace(browser: Browser):
    context = browser.new_context()
    context.tracing.start(screenshots=True, snapshots=True, sources=True)
    page = context.new_page()

    with context.tracing.group("Open the practice page"):
        page.goto("https://sqatools.in/automation-practice-page/")

    with context.tracing.group("Fill the form"):
        page.locator("#username").fill("trace_user")
        page.locator("#male").check()

    context.tracing.stop(path="traces/practice-trace.zip")
    context.close()

    names = zipfile.ZipFile("traces/practice-trace.zip").namelist()
    print("\ntrace files:", sorted(n for n in names if "/" not in n))
    for folder in ["resources/", "screencast/", "src/"]:
        print(f"{folder:<12}:", sum(n.startswith(folder) for n in names), "files")
  • tracing.start() options: screenshots (the filmstrip timeline), snapshots (DOM snapshots and network activity for every action) and sources (your source code, shown next to each action).
  • tracing.stop(path=...) writes the zip. Call it before context.close().
  • tracing.group("name") collects the actions inside the with block under one heading in the Trace Viewer, so a long test reads like a list of steps.
  • trace.trace holds the actions and snapshots, trace.network the network log and trace.stacks the call stacks. The folders hold page resources (resources/), the filmstrip images (screencast/) and your Python source files (src/).

📝 Note: In Python, expect() calls are recorded in the trace too, as actions named like *Expect “to_have_text”*, because each assertion runs in the browser. You will see this in the Trace Viewer below.

⌨️ Terminal

pytest -q -s tests

🖥️ Output

viewport : (1280, 720)
full page: (1280, 8894)
clip     : (400, 300)
.
table    : (740, 172)
viewport.png: 61,548 bytes
viewport.jpg: 30,305 bytes
.
trace files: ['trace.network', 'trace.stacks', 'trace.trace']
resources/  : 17 files
screencast/ : 12 files
src/        : 9 files
.
video: videos/<random name>.webm, video.stat().st_size > 0 = True
.
4 passed, 1 warning in 9.73s

🔬 Reading a Trace in the Trace Viewer

Open a trace with the Playwright CLI that comes with the Python package:

⌨️ Terminal

playwright show-trace test-results/demos-test-checkout-py-test-wrong-heading-chromium/trace.zip

You can also drag the zip file onto trace.playwright.dev. The trace is opened in your browser; it is not uploaded to a server.

The Trace Viewer of the failed test above shows:

  • Timeline (top): a filmstrip of screenshots over time. Hover over it to see the page at any moment.
  • Actions (left): every step in order with its duration. For this test: *Create page*, *Navigate* (2.1 s) and *Expect “to_have_text”* (2.0 s), shown in red because it failed. Click an action to select it.
  • Action / Before / After (centre): the DOM snapshot of the page at that step. It is a real snapshot, not a picture: you can inspect elements, and the element the action used (here the h1) is highlighted.
  • Bottom tabs: *Locator* (try locators against the snapshot), *Call* (the parameters, such as the expected text “Checkout” and the 2000 ms timeout), *Log* (the same call log as in the terminal), *Errors*, *Console*, *Network* (every request, 35 in this test), *Source* (your Python code with the line highlighted) and *Attachments*.
  • Metadata (next to Actions): the browser, viewport and other context settings.

💡 Tip: Start every investigation from the Errors tab, then step back through the Actions list and compare the Before and After snapshots until you find the step where the page stopped matching your expectation.


🏋️ 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: Take a full-page screenshot of the practice page and a screenshot of only the web table, masking the username field.

Show answer
page.screenshot(path="shots/full.png", full_page=True, mask=[page.locator("#username")])
page.locator("table").first.screenshot(path="shots/table.png")

Exercise 2: Configure pytest.ini so every failed test keeps a screenshot, a video and a trace in artifacts/.

Show answer
[pytest]
addopts = --screenshot only-on-failure --video retain-on-failure --tracing retain-on-failure --output artifacts

Exercise 3: Record a video for a manually created context and print where it was saved.

Show answer
context = browser.new_context(record_video_dir="videos/")
page = context.new_page()
page.goto("https://sqatools.in/automation-practice-page/")
context.close()                     # the video is written when the context closes
print(page.video.path())

🧠 MCQ Quiz: Screenshots, Videos and Traces on Failure

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 option captures the whole scrollable page?
  2. How do you screenshot a single element?
  3. What does the mask option do?
  4. What does page.screenshot() return when no path is given?
  5. Which pytest-playwright option keeps videos only for failed tests?
  6. When is a context’s video file written?
  7. Where do pytest-playwright artifacts go by default?
  8. What does --full-page-screenshot change?
  9. Which format option makes smaller screenshots?
  10. Why keep traces in addition to screenshots for failures?

Want a longer, timed test? Take the Module 5 mock interview (20 MCQs in 20 minutes).


❓ Frequently Asked Questions

🤔 How do I take a screenshot only when a test fails in Playwright Python?

Run pytest with --screenshot only-on-failure, or add it to addopts in pytest.ini. The screenshot is saved as test-failed-1.png in the test’s folder inside test-results.

🤔 Why is there no video for my passing test?

With --video retain-on-failure, videos of passing tests are deleted at the end of the test. Use --video on to keep every video.

🤔 Can I change the screenshot file name?

The automatic files always use pytest-playwright’s names. For your own names, call page.screenshot(path="...") in the test, or in a fixture that runs after the test.

🤔 Where are the screenshots saved?

In the folder set by --output, test-results by default, with one subfolder per test. pytest-playwright clears that folder at the start of each run.

🤔 Should I keep traces for every test?

Usually not. Traces are the most detailed artifact and the largest. Use --tracing retain-on-failure so only failed tests keep one.


🏁 Summary

  • page.screenshot() captures the viewport, full_page=True the whole page, clip= a rectangle and locator.screenshot() one element.
  • mask=, mask_color= and style= hide sensitive or changing content; type="jpeg" and quality= make smaller files.
  • pytest-playwright’s --screenshot, --video and --tracing options capture evidence automatically; only-on-failure and retain-on-failure keep it only for failed tests.
  • Artifacts go to test-results/<test-id>/ (test-failed-1.png, video.webm, trace.zip), and are added to pytest-html reports.
  • record_video_dir and context.tracing record from code; tracing.group() organises a trace into steps.
  • playwright show-trace trace.zip or trace.playwright.dev opens a trace for step-by-step debugging.

Next, you will use screenshots for more than evidence: visual regression testing compares them with approved baseline images to catch unwanted UI changes.

🎬 Watch the Playwright tutorial series on YouTube!

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

Auto-Waiting and Explicit Waits in Playwright Python

Flaky tests are almost always waiting problems: the test acts or checks before the page is ready. Playwright for Python removes most of them with auto-waiting, so you rarely write a wait yourself. In this lesson you will see exactly what Playwright waits for before each action, which explicit waits exist for the remaining cases (navigation, elements, JavaScript conditions and network responses), how to set timeouts, and why time.sleep() does not belong in a test.

📖 What You’ll Learn: actionability checks (visible, stable, receives events, enabled, editable), what happens when an element never becomes actionable, force=True, goto wait_until options (commit, domcontentloaded, load, networkidle), wait_for_url, locator.wait_for with states, page.wait_for_function, expect_response and expect_request, action, navigation and assertion timeouts and how to change them, why wait_for_timeout and time.sleep are flaky, and a simple polling helper for non-page conditions.


🤔 Why Waiting Matters

A browser does many things asynchronously: it downloads files, runs JavaScript, starts animations and waits for servers. Your test code runs much faster than all of that. If the test clicks a button before it exists, or reads a text before the server has answered, the test fails, even though a real user would have seen a working page.

Older tools solve this with waits written by hand: “sleep 3 seconds”, or “wait until the element is clickable” before every step. Playwright takes a different approach:

  1. Actions auto-wait. click(), fill(), check() and the others wait until the element is ready.
  2. Assertions retry. expect(...) keeps checking until the page matches (previous lesson).
  3. Explicit waits exist for the few cases left: navigation, network responses and custom conditions.

⚙️ Auto-Waiting: The Actionability Checks

Before an action, Playwright first finds exactly one element for the locator, then checks that the element is actionable. Which checks run depends on the action:

ActionVisibleStableReceives eventsEnabledEditable
click(), dblclick(), check(), uncheck(), set_checked(), tap()YesYesYesYes–
hover(), drag_to()YesYesYes––
fill(), clear()Yes––YesYes
select_option()Yes––Yes–
screenshot()YesYes–––
press(), press_sequentially(), focus(), set_input_files(), dispatch_event()–––––

(Source: the official Playwright Python “Auto-waiting” guide.)

What each check means:

  • Visible: the element has a size, and is not visibility:hidden or display:none. An element with opacity:0 counts as visible.
  • Stable: the element kept the same position and size for two animation frames, so it is not sliding or growing.
  • Receives events: nothing else, such as an overlay or a cookie banner, covers the point Playwright will click.
  • Enabled: no disabled attribute (also through a disabled <fieldset>), and not inside aria-disabled="true".
  • Editable: enabled and not read-only.

Seeing auto-waiting work

To show auto-waiting clearly, this test builds a tiny page with page.set_content(). The button starts disabled, and a loading overlay covers it. After one second the overlay disappears; after 1.5 seconds the button becomes enabled. The test contains no wait at all:

📄 tests/test_auto_wait.py

import time

from playwright.sync_api import Page, expect

SLOW_PAGE = """
<div id="overlay" style="position:fixed; inset:0; background:#0008">Loading...</div>
<button id="save" disabled onclick="this.textContent='Saved'">Save</button>
<script>
  setTimeout(() => document.getElementById('overlay').remove(), 1000);
  setTimeout(() => document.getElementById('save').disabled = false, 1500);
</script>
"""


def test_click_waits_until_the_button_is_ready(page: Page):
    page.set_content(SLOW_PAGE)
    start = time.monotonic()

    page.get_by_role("button", name="Save").click()     # waits for: no overlay + enabled

    print(f"\nclicked after {time.monotonic() - start:.1f} s")
    expect(page.get_by_role("button")).to_have_text("Saved")
  • page.set_content(html) loads HTML directly into the page. It is handy for demonstrating one behaviour in isolation.
  • click() kept waiting until the button was enabled and nothing covered it, then clicked.
  • In our run it printed clicked after 2.0 s, a little later than 1.5 s: Playwright re-checks the element in a loop, so it acts on a check shortly after the page becomes ready, not at the exact moment it changes.
  • time.monotonic() is used only to print how long the click waited.

When an element never becomes actionable

If the checks do not pass within the action timeout, the action fails with a TimeoutError that explains what it was waiting for. Here the overlay never goes away:

📄 demos/test_blocked_click.py

from playwright.sync_api import Page

BLOCKED = """
<div id="cookie-banner" style="position:fixed; inset:0; background:#0008">We use cookies</div>
<button>Buy now</button>
"""


def test_button_covered_by_a_banner(page: Page):
    page.set_content(BLOCKED)
    page.get_by_role("button", name="Buy now").click(timeout=3_000)

⌨️ Terminal

pytest -q demos/test_blocked_click.py

🖥️ Output

E           playwright._impl._errors.TimeoutError: Locator.click: Timeout 3000ms exceeded.
E           Call log:
E             - waiting for get_by_role("button", name="Buy now")
E               - locator resolved to <button>Buy now</button>
E             - attempting click action
E               2 × waiting for element to be visible, enabled and stable
E                 - element is visible, enabled and stable
E                 - scrolling into view if needed
E                 - done scrolling
E                 - <div id="cookie-banner">We use cookies</div> intercepts pointer events
E               - retrying click action
E               - waiting 20ms
E               2 × waiting for element to be visible, enabled and stable
E                 - element is visible, enabled and stable
E                 - scrolling into view if needed
E                 - done scrolling
E                 - <div id="cookie-banner">We use cookies</div> intercepts pointer events
E               - retrying click action
E                 - waiting 100ms
E               5 × waiting for element to be visible, enabled and stable
E                 - element is visible, enabled and stable
E                 - scrolling into view if needed
E                 - done scrolling
E                 - <div id="cookie-banner">We use cookies</div> intercepts pointer events
E               - retrying click action
E                 - waiting 500ms
E               - waiting for element to be visible, enabled and stable

..\_venv0\Lib\site-packages\playwright\_impl\_connection.py:636: TimeoutError
=========================== short test summary info ===========================
FAILED demos/test_blocked_click.py::test_button_covered_by_a_banner[chromium]
1 failed, 1 warning in 3.64s
  • The call log is your best debugging tool. Here it says the <div id="cookie-banner"> intercepts pointer events, so the fix is to close the banner first, not to add a sleep.
  • timeout=3_000 limits this one action to 3 seconds. Without it, the default action timeout applies (30 seconds in pytest-playwright).

⚠️ Watch out: click(force=True) skips the “receives events” and other non-essential checks. It makes this test pass, but a real user could not click that button. Use force=True only when you understand why the check fails and it does not matter for the test.


🧭 Waiting for Navigation: wait_until

page.goto() waits for the page to load before it returns. The wait_until argument decides what “loaded” means:

wait_untilgoto() returns when…
"commit"The server’s response arrived and the document started loading
"domcontentloaded"The HTML is parsed (the DOMContentLoaded event)
"load" (default)The page and all its resources, such as images, styles and scripts, have loaded
"networkidle"No network request for 500 ms (discouraged by Playwright)

📄 tests/test_navigation.py

import time

from playwright.sync_api import Page, expect

URL = "https://sqatools.in/automation-practice-page/"


def test_wait_until_options(page: Page):
    for state in ["commit", "domcontentloaded", "load"]:
        start = time.monotonic()
        response = page.goto(URL, wait_until=state)
        print(f"\n{state:>16}: {time.monotonic() - start:.2f} s, status {response.status}")

    # Whatever wait_until you choose, check readiness with an assertion
    expect(page.get_by_role("heading", name="Text Fields")).to_be_visible()

One run printed these timings (the full run at the end of the lesson shows another; the numbers vary):

🖥️ Output

          commit: 0.14 s, status 200
domcontentloaded: 0.17 s, status 200
            load: 2.61 s, status 200
  • goto() returns the main Response, so you can check its status code.
  • The numbers change from run to run, but the order is always the same: commit is the earliest, load the latest.
  • "load" waits for every image, font and third-party script. Some sites load slow third-party resources: while preparing this course, the load event of a public demo site sometimes took longer than the 30-second navigation timeout. When that happens, use wait_until="domcontentloaded" and then wait for the element you actually need with expect().

📝 Note: Why is "networkidle" discouraged? Many modern pages never become idle: analytics, chat widgets and polling keep sending requests. Your test then waits until the timeout. Wait for something the user can see instead.

After a click that navigates: wait_for_url

goto() waits by itself. But when a click starts the navigation, wait for the new URL:

📄 tests/test_navigation.py

def test_click_then_wait_for_url(page: Page):
    page.set_content(f'<a href="{URL}">Open the practice page</a>')
    page.get_by_role("link", name="Open the practice page").click()

    page.wait_for_url("**/automation-practice-page/")     # glob pattern
    expect(page).to_have_url(URL)                       # the assertion form also waits
    expect(page).to_have_title("Automation Practice Page - SQA Tools")
  • wait_for_url() accepts an exact URL, a glob (** matches any characters, including /), a regex or a function.
  • expect(page).to_have_url(...) waits too. Prefer it when you also want the check to appear as an assertion in your test.
  • wait_for_url() also takes wait_until=, so you can return as soon as the new URL has committed.

🔍 Waiting for an Element: locator.wait_for()

Sometimes you need to wait for an element without acting on it or asserting it, for example before reading a list of values. locator.wait_for() waits for one of four states:

state=Waits until the element…
"visible" (default)is in the DOM and visible
"hidden"is not visible, or not in the DOM
"attached"is in the DOM (visible or not)
"detached"is removed from the DOM

The practice page has an auto-suggest box: typing into the search field shows matching suggestions below it.

📄 tests/test_locator_wait.py

from playwright.sync_api import Page


def test_wait_for_suggestions(page: Page):
    page.goto("https://sqatools.in/automation-practice-page/")
    search = page.locator("#searchBox")
    suggestions = page.locator("#suggestions div")

    search.press_sequentially("pl")
    suggestions.first.wait_for()                       # state="visible" by default
    print("\nsuggestions:", suggestions.all_inner_texts())

    search.fill("")                                    # empty input hides the box
    page.locator("#suggestions").wait_for(state="hidden")
    print("box hidden, suggestion items left:", suggestions.count())
  • all_inner_texts() does not wait; it returns whatever is in the page right now. That is why the test waits for the first suggestion before reading the list.
  • wait_for() is strict: if the locator matches several elements, it raises a strict mode violation for any state. That is why this test uses .first.
  • Typing “pl” matches only “Playwright” in the page’s suggestion list, so one item appears.
  • count() does not wait either. The page empties the box when the input is cleared, so the count is 0 after the box is hidden.

💡 Tip: If you can express the wait as an assertion, do: expect(suggestions).to_have_count(2) waits and checks in one line. Use wait_for() when you only need the page to be ready before reading data.


🧮 Waiting for a JavaScript Condition: wait_for_function

When the condition is easier to describe in JavaScript, page.wait_for_function() runs your expression in the browser again and again until it returns a truthy value:

📄 tests/test_wait_function.py

import time

from playwright.sync_api import Page


def test_wait_for_ajax_text(page: Page):
    page.goto("https://sqatools.in/automation-practice-page/")
    page.get_by_role("button", name="Load Success").click()

    start = time.monotonic()
    page.wait_for_function(
        "() => document.querySelector('#loader').innerText.includes('loaded')"
    )
    print(f"\nloaded after {time.monotonic() - start:.1f} s:", page.locator("#loader").inner_text())
  • The expression runs inside the page, so it can read anything JavaScript can: element text, global variables, localStorage and more.
  • By default it re-checks on every animation frame. Pass polling=500 to check every 500 ms instead.
  • Pass Python values to the function with arg=: page.wait_for_function("n => document.querySelectorAll('tr').length >= n", arg=4).

🌐 Waiting for Network Traffic: expect_response

To wait for a specific request or response, wrap the action that triggers it in a with block:

📄 tests/test_network_wait.py

from playwright.sync_api import Page


def test_wait_for_the_page_response(page: Page):
    with page.expect_response("**/automation-practice-page/") as response_info:
        page.goto("https://sqatools.in/automation-practice-page/")

    response = response_info.value
    print(f"\n{response.status} {response.request.method} {response.url}")
    assert response.ok


def test_wait_for_a_request(page: Page):
    with page.expect_request(lambda r: r.resource_type == "document") as request_info:
        page.goto("https://sqatools.in/automation-practice-page/")

    print("\nrequest:", request_info.value.method, request_info.value.resource_type)
  • Start waiting before the action: the with block registers the listener, then the action runs inside it. If the response came first, a wait started afterwards could miss it.
  • response_info.value holds the Response once the block ends.
  • The matcher can be a URL glob, a regex or a function that receives the response (or request).
  • In a real application, use this for the API call behind a button: with page.expect_response("**/api/orders") as r: page.get_by_role("button", name="Place order").click(). Module 8 covers network testing in depth.

⏱️ Timeouts: Actions, Navigation and Assertions

WhatDefaultChange it with
Actions (click, fill, …) and wait_for*30 spage.set_default_timeout() or timeout=
Navigation (goto, wait_for_url, reload, …)30 spage.set_default_navigation_timeout() or timeout=
expect(...) assertions5 sexpect.set_options(timeout=...) or timeout=

All values are in milliseconds. set_default_navigation_timeout() takes priority over set_default_timeout() for navigation methods. The same two methods also exist on the browser context.

To change them for every test, override the page fixture in conftest.py. A fixture with the same name as the plugin’s fixture can request it and adjust it:

📄 timeouts/conftest.py

import pytest
from playwright.sync_api import Page


@pytest.fixture
def page(page: Page) -> Page:
    page.set_default_timeout(10_000)               # actions and waits: 10 s
    page.set_default_navigation_timeout(45_000)    # goto, reload, wait_for_url: 45 s
    return page

📄 timeouts/test_timeouts.py

from playwright.sync_api import Page, TimeoutError


def test_default_timeout_applies(page: Page):
    page.goto("https://sqatools.in/automation-practice-page/")
    try:
        page.locator("#doesNotExist").click(timeout=1_000)   # timeout= overrides the default
    except TimeoutError as error:
        print("\n" + str(error).splitlines()[0])

⌨️ Terminal

pytest -q -s timeouts

🖥️ Output

Locator.click: Timeout 1000ms exceeded.
.
1 passed, 1 warning in 3.11s
  • TimeoutError is imported from playwright.sync_api; it is not Python’s built-in TimeoutError.
  • Catching it is useful in helpers (for example, “close the promo popup if it appears”), but in a normal test let it fail so you see the call log.
  • Pass timeout=0 to wait without a limit. Avoid it in tests: a stuck test then never finishes.

🚫 Hard Waits: wait_for_timeout and time.sleep

page.wait_for_timeout(3_000)   # waits 3 s, always

A fixed wait is always wrong in one direction: on a fast run it wastes time, and on a slow run (a busy CI server) it is too short and the test fails. The Playwright documentation states that wait_for_timeout() should only be used for debugging.

time.sleep() is worse in the sync API: it blocks the Python thread, so Playwright cannot process browser events during the sleep. This test proves it with a console message the page logs after 200 ms:

📄 tests/test_sleep_vs_wait.py

import time

from playwright.sync_api import Page


def test_events_are_not_processed_during_sleep(page: Page):
    messages = []
    page.on("console", lambda msg: messages.append(msg.text))
    page.evaluate("setTimeout(() => console.log('hello'), 200)")

    time.sleep(1)                           # 1 s passes, but no event is handled
    print("\nafter time.sleep:", messages)

    page.wait_for_timeout(10)               # Playwright gets control and delivers the event
    print("after wait_for_timeout:", messages)

🖥️ Output

after time.sleep: []
after wait_for_timeout: ['hello']

The message was logged during the sleep, but your page.on("console") handler only ran once Playwright had control again. The same applies to dialog handlers and other events. If you must pause while debugging, use page.wait_for_timeout(), then replace it with a real condition:

Instead of a hard wait for…Use
An element to appearexpect(locator).to_be_visible()
A text to changeexpect(locator).to_have_text("...")
A new page after a clickpage.wait_for_url(...) or expect(page).to_have_url(...)
A server call to finishwith page.expect_response(...)
A spinner to go awayexpect(spinner).to_be_hidden()

🔁 Polling a Non-Page Condition

The TypeScript test runner has expect.poll() and toPass() for retrying arbitrary code. Playwright for Python does not have them: expect() accepts only a Page, Locator or APIResponse. For a condition outside the page, such as a file appearing on disk or a record reaching a database, write a small helper:

📄 tests/helpers.py

import time
from typing import Callable


def wait_until(condition: Callable[[], bool], timeout: float = 10.0, interval: float = 0.25) -> None:
    """Call condition() until it returns True, or raise after timeout seconds."""
    deadline = time.monotonic() + timeout
    while time.monotonic() < deadline:
        if condition():
            return
        time.sleep(interval)
    raise AssertionError(f"Condition not met within {timeout} s")

📄 tests/test_polling.py

import threading
from pathlib import Path

from helpers import wait_until


def test_wait_for_a_file(tmp_path: Path):
    report = tmp_path / "report.csv"

    # Something else creates the file after 1 second (here: a timer thread)
    threading.Timer(1.0, report.write_text, args=["id,status\n1,passed\n"]).start()

    wait_until(report.exists, timeout=5)
    assert report.read_text().startswith("id,status")
  • This test uses no browser, so time.sleep() inside the helper is fine. Do not use this helper for page content; expect() already does it better.
  • from helpers import wait_until works because pytest adds the test’s folder (with no __init__.py) to sys.path in its default import mode.

⌨️ Terminal

pytest -q -s tests

🖥️ Output

clicked after 2.0 s
.
suggestions: ['Playwright']
box hidden, suggestion items left: 0
.
          commit: 0.14 s, status 200

domcontentloaded: 0.17 s, status 200

            load: 1.85 s, status 200
..
200 GET https://sqatools.in/automation-practice-page/
.
request: GET document
.
after time.sleep: []
after wait_for_timeout: ['hello']
.
loaded after 3.0 s: Data loaded successfully!
..
9 passed, 1 warning in 22.57s

🏋️ 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: Replace the sleep in this code with a proper wait:

page.get_by_role("button", name="Load Success").click()
time.sleep(3)
assert page.locator("#loader").inner_text() == "Data loaded successfully!"
Show answer
page.get_by_role("button", name="Load Success").click()
expect(page.locator("#loader")).to_have_text("Data loaded successfully!")

The assertion waits only as long as needed (up to its timeout) and fails with a clear message.

Exercise 2: Wait until the SQA Shop URL changes to the cart after clicking the cart link, then until the cart title is visible.

Show answer
page.get_by_test_id("cart-link").click()
page.wait_for_url(re.compile(r"#/cart$"))
page.get_by_test_id("cart-title").wait_for(state="visible")

Exercise 3: Wait for a JavaScript condition: the page variable window.appReady becomes true.

Show answer
page.wait_for_function("() => window.appReady === true")

Prefer waiting for something visible to users when possible; use wait_for_function for app state with no visible sign.


🧠 MCQ Quiz: Auto-Waiting and Explicit Waits

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 is NOT an actionability check before a click?
  2. What does wait_until="domcontentloaded" mean for goto?
  3. Why is networkidle discouraged?
  4. Which method waits for an element to disappear?
  5. What is the default timeout for actions like click?
  6. How do you change the default action timeout for a page?
  7. Why avoid page.wait_for_timeout(3000) in tests?
  8. Which wait is best after clicking a button that calls an API?
  9. What happens when an element never becomes enabled before a click times out?
  10. What does wait_for_url accept?

Want a longer, timed test? Take the Module 5 mock interview (20 MCQs in 20 minutes).


❓ Frequently Asked Questions

🤔 Do I need wait_for_selector in Playwright Python?

Rarely. page.wait_for_selector() still works, but the recommended style is locators: actions auto-wait, expect() waits for states, and locator.wait_for() covers the rest.

🤔 Why does my test pass locally but time out in CI?

CI machines are often slower and may have a different network. Look at the call log: it tells you what Playwright was waiting for. Fix the cause (an overlay, a slow third-party script, a missing test user) rather than raising every timeout.

🤔 What is the default timeout in Playwright Python?

With pytest-playwright, actions and navigation have a 30-second default, and expect() assertions 5 seconds. You can change each one, as shown in the timeouts section.

🤔 Is wait_until=”networkidle” a good idea for single-page apps?

Usually not. Playwright marks it as discouraged because pages with polling, analytics or websockets may never be idle. Wait for a visible result with expect() instead.

🤔 Does fill() wait for the field to be enabled?

Yes. fill() waits until the element is visible, enabled and editable. If the field stays disabled, it fails with a TimeoutError whose call log says “element is not enabled”.


🏁 Summary

  • Actions auto-wait for actionability: visible, stable, receiving events, enabled and editable, depending on the action.
  • The call log of a TimeoutError tells you exactly which check failed.
  • goto() waits for load by default; domcontentloaded helps with slow third-party resources. Avoid networkidle.
  • Use wait_for_url() after clicks that navigate, locator.wait_for() before reading data, wait_for_function() for JavaScript conditions and expect_response() for network calls.
  • Change timeouts with set_default_timeout(), set_default_navigation_timeout(), expect.set_options() or timeout=.
  • Replace wait_for_timeout() and time.sleep() with a real condition.

Next, you will capture evidence when a test fails: screenshots, videos and traces.

🎬 Watch the Playwright tutorial series on YouTube!

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

Playwright Python Assertions with expect (Web-First Assertions)

A test is only as good as its checks. Playwright for Python ships a dedicated assertion library, expect, built for web pages that change over time: every expect check keeps retrying until the page reaches the expected state or a timeout runs out. In this lesson you will use every important assertion on the SQA Tools practice page, see why a plain assert can be flaky on a dynamic page, and learn negation, custom messages, timeouts and soft assertions.

📖 What You’ll Learn: what web-first assertions are and how they retry, page assertions (to_have_title, to_have_url), visibility and state assertions, text assertions (exact, partial, regex, lists, ignore_case), value, attribute, class, CSS, id and count assertions, accessibility assertions, API response assertions, not_ negation, custom failure messages, per-assertion and global timeouts, soft assertions with expect.soft, and when a plain assert is the right tool.


🎯 What Is a Web-First Assertion?

An assertion checks that the application is in the state you expect. If the check fails, the test fails.

Python already has the assert statement, and pytest makes it powerful (you used it in Module 3). So why does Playwright add its own expect function?

Because web pages change after your action. Click “Load Success” on the practice page, and the text below the button shows “Loading…” first. It changes to “Data loaded successfully!” 3 seconds later. A check that reads the text once, right after the click, sees the wrong text and fails, even though the page works perfectly.

expect() solves this. It retries the check again and again until it passes or the timeout runs out (5 seconds by default). That is what “web-first” means: the assertion waits for the page, like a human tester would.

from playwright.sync_api import expect

expect(page.locator("#loader")).to_have_text("Data loaded successfully!")
  • expect(...) takes a Locator, a Page or an APIResponse.
  • It returns an assertions object with methods such as to_have_text(), to_be_visible() and to_have_url().
  • Each method retries until it passes, or raises AssertionError after the timeout.

All examples below run against the SQA Tools practice page. Every test receives the opened page from this fixture:

📄 tests/conftest.py

import pytest
from playwright.sync_api import Page


@pytest.fixture
def practice(page: Page) -> Page:
    page.goto("https://sqatools.in/automation-practice-page/")
    return page

📄 Page Assertions: Title and URL

📄 tests/test_page_assertions.py

import re

from playwright.sync_api import Page, expect


def test_title_and_url(practice: Page):
    # Exact title
    expect(practice).to_have_title("Automation Practice Page - SQA Tools")

    # Part of the title, with a regular expression
    expect(practice).to_have_title(re.compile("Practice Page"))

    # Exact URL, then a URL pattern
    expect(practice).to_have_url("https://sqatools.in/automation-practice-page/")
    expect(practice).to_have_url(re.compile(r"/automation-practice-page/$"))
  • Pass the page itself (not a locator) to expect() for page-level checks.
  • A plain string must match exactly. Use re.compile(...) when only part of the value matters, for example a URL that contains an id or a query string.
  • to_have_url() is the right check after a click that navigates: it waits for the new URL instead of reading page.url too early.

👀 Visibility and Presence

📄 tests/test_locator_assertions.py

import re

from playwright.sync_api import Page, expect


def test_visibility(practice: Page):
    # Visible on screen (has a size, not display:none or visibility:hidden)
    expect(practice.locator("#username")).to_be_visible()

    # The hidden field exists in the HTML but has style="display:none;"
    hidden = practice.locator("#hiddenField")
    expect(hidden).to_be_hidden()
    expect(hidden).to_be_attached()          # present in the DOM, even though hidden

    # An element that does not exist at all
    missing = practice.locator("#doesNotExist")
    expect(missing).not_to_be_attached()
    expect(missing).to_be_hidden()           # "hidden" also passes when nothing matches

    # In the viewport: the "Bottom of Page" heading is far below the first screen
    bottom = practice.get_by_role("heading", name="Bottom of Page")
    expect(bottom).not_to_be_in_viewport()
    bottom.scroll_into_view_if_needed()
    expect(bottom).to_be_in_viewport()
AssertionPasses when
to_be_visible()The element is rendered and has a size
to_be_hidden()The element is invisible or does not exist
to_be_attached()The element is in the DOM (visible or not)
to_be_in_viewport()The element is inside the visible part of the window

📝 Note: to_be_hidden() passing for a missing element is by design: the user cannot see it either way. If you need to prove an element is *in the HTML but hidden*, combine to_be_attached() with to_be_hidden(), as the test above does.


🔘 Element State: Enabled, Editable, Checked, Focused, Empty

📄 tests/test_locator_assertions.py

def test_states(practice: Page):
    expect(practice.locator("#disabledInput")).to_be_disabled()

    username = practice.locator("#username")
    expect(username).to_be_enabled()
    expect(username).to_be_editable()
    expect(username).to_be_empty()           # an input with no value

    username.fill("qa_learner")
    expect(username).not_to_be_empty()

    username.focus()
    expect(username).to_be_focused()

    # Checkboxes and radio buttons
    practice.locator("#java").check()
    expect(practice.locator("#java")).to_be_checked()
    expect(practice.locator("#python")).not_to_be_checked()
    expect(practice.locator("#python")).to_be_checked(checked=False)   # same as the line above
  • to_be_empty() works for inputs (no value) and for other elements (no text).
  • to_be_editable() fails for disabled and read-only fields.
  • to_be_checked(checked=False) is another way to write not_to_be_checked(); it is handy when the expected state comes from a variable.

📝 Text Assertions

Text is what you check most often, and there are two main methods:

  • to_have_text() – the element’s whole text must match.
  • to_contain_text() – the expected text must appear somewhere in the element’s text.

📄 tests/test_locator_assertions.py

def test_text(practice: Page):
    submit = practice.locator("#submitButton")

    # Exact (whitespace at the ends is ignored) and partial
    expect(submit).to_have_text("Submit")
    expect(practice.locator(".drag")).to_contain_text("Drag Me")

    # Case-insensitive
    expect(submit).to_have_text("SUBMIT", ignore_case=True)

    # Regular expression: a heading that starts with "Ultimate"
    expect(practice.locator("h1").nth(1)).to_have_text(re.compile(r"^Ultimate"))

    # A list checks several elements at once, in order
    first_row_cells = practice.locator("table tbody tr").first.locator("td")
    expect(first_row_cells).to_have_text(["1", "Deepesh", "Trainer"])

    # The "Name" column contains these names, in this order
    names = practice.locator("table tbody td:nth-child(2)")
    expect(names).to_contain_text(["Deep", "Rah", "Ani"])
  • With a list, to_have_text() requires the locator to match exactly that many elements, each with the matching text, in that order. It is the fastest way to verify a table row or a menu.
  • to_contain_text() with a list checks each element in order for the partial text.
  • Earlier lessons used to_contain_text() on the drag box because an advertising script inserts a “Try Cloud Tools” link inside it on the live site. When a page can contain extra content, check only the part that matters.

💡 Tip: Do not compare text with assert locator.inner_text() == "...". That reads the text once. expect(locator).to_have_text("...") retries, normalises whitespace and prints a clear diff on failure.


🧾 Values, Attributes, Classes, CSS and Count

📄 tests/test_locator_assertions.py

def test_values_and_attributes(practice: Page):
    # Input values
    username = practice.locator("#username")
    username.fill("qa_learner")
    expect(username).to_have_value("qa_learner")
    expect(practice.locator("#address")).to_have_value("Enter address")   # pre-filled textarea

    # Dropdowns: one value, or several for a multi-select
    practice.locator("#country").select_option("uk")
    expect(practice.locator("#country")).to_have_value("uk")
    practice.locator("#skills").select_option(["Python", "Playwright"])
    expect(practice.locator("#skills")).to_have_values(["Python", "Playwright"])

    # Attributes
    expect(username).to_have_attribute("placeholder", "Enter username")
    expect(practice.locator("#googleLink")).to_have_attribute("target", "_blank")
    expect(practice.locator("#googleLink")).to_have_attribute("href", re.compile("google"))

    # id, class, CSS and count
    expect(practice.locator(".drag")).to_have_id("drag1")
    expect(practice.locator(".drag")).to_have_class("drag")
    expect(practice.locator(".drop")).to_contain_class("drop")
    expect(practice.locator("#hiddenField")).to_have_css("display", "none")
    expect(practice.locator("table tbody tr")).to_have_count(3)

    # A DOM property (not an HTML attribute)
    expect(practice.locator("#disabledInput")).to_have_js_property("disabled", True)
AssertionChecks
to_have_value(v)The current value of an input, textarea or single select
to_have_values([..])The selected options of a multi-select
to_have_attribute(name, v)An HTML attribute (string or regex)
to_have_id(id)The id attribute
to_have_class(c)The full class attribute (string, regex or list)
to_contain_class(c)One or more classes are present, in any order
to_have_css(prop, v)A computed CSS value
to_have_count(n)How many elements the locator matches
to_have_js_property(name, v)A JavaScript property of the element
  • to_have_class("drag") compares the whole class attribute. If an element has class="btn btn-primary", to_have_class("btn") fails, while to_contain_class("btn") passes.
  • to_have_css() checks the computed style, so it also covers styles that come from a stylesheet, not just the style attribute.
  • to_have_count(0) is a clear way to say “no such element”, for example “no error messages”.

♿ Accessibility Assertions

These check what a screen reader would announce. They are also a quick way to keep your role-based locators honest:

📄 tests/test_locator_assertions.py

def test_accessibility(practice: Page):
    hover = practice.locator("#hoverButton")
    expect(hover).to_have_role("button")
    expect(hover).to_have_accessible_name("Hover Over Me")

    # A checkbox gets its accessible name from its <label for="java">
    expect(practice.locator("#java")).to_have_accessible_name("Java")

Playwright also has to_have_accessible_description() and to_have_accessible_error_message() for form fields that use aria-describedby or aria-errormessage.


🌐 API Response Assertions

expect() also accepts an APIResponse. You will use it a lot in the API testing module; here is a first taste:

📄 tests/test_api_assertion.py

from playwright.sync_api import Page, expect


def test_page_responds(page: Page):
    response = page.request.get("https://sqatools.in/automation-practice-page/")
    expect(response).to_be_ok()        # status code 200-299
    assert response.status == 200
  • page.request sends HTTP requests that share the browser context’s cookies.
  • to_be_ok() passes for status codes 200 to 299. On failure, it prints the response details.

Run all the passing tests:

⌨️ Terminal

pytest -q tests

🖥️ Output

........                                                                 [100%]
8 passed, 1 warning in 18.62s

⏳ Why a Plain assert Can Be Flaky

Here is the “Load Success” button checked two ways. First, the right way:

📄 tests/test_retry.py

from playwright.sync_api import Page, expect


def test_expect_waits_for_the_ajax_result(practice: Page):
    practice.get_by_role("button", name="Load Success").click()

    loader = practice.locator("#loader")
    expect(loader).to_have_text("Loading...")
    expect(loader).to_have_text("Data loaded successfully!")   # arrives after 3 s; expect waits

Now the same check with a plain assert:

📄 demos/test_plain_assert.py

import pytest
from playwright.sync_api import Page


@pytest.fixture
def practice(page: Page) -> Page:
    page.goto("https://sqatools.in/automation-practice-page/")
    return page


def test_plain_assert_reads_too_early(practice: Page):
    practice.get_by_role("button", name="Load Success").click()

    # inner_text() reads the text ONCE, immediately after the click
    assert practice.locator("#loader").inner_text() == "Data loaded successfully!"

⌨️ Terminal

pytest -q demos/test_plain_assert.py

🖥️ Output

F                                                                        [100%]
================================== FAILURES ===================================
_________________ test_plain_assert_reads_too_early[chromium] _________________

practice = <Page url='https://sqatools.in/automation-practice-page/'>

    def test_plain_assert_reads_too_early(practice: Page):
        practice.get_by_role("button", name="Load Success").click()
    
        # inner_text() reads the text ONCE, immediately after the click
>       assert practice.locator("#loader").inner_text() == "Data loaded successfully!"
E       AssertionError: assert 'Loading...' == 'Data loaded successfully!'
E         
E         - Data loaded successfully!
E         + Loading...

demos\test_plain_assert.py:15: AssertionError
=========================== short test summary info ===========================
FAILED demos/test_plain_assert.py::test_plain_assert_reads_too_early[chromium]
1 failed, 1 warning in 2.72s

The page is fine; the test is wrong. inner_text() returned “Loading…” because it ran before the 3-second timer finished.

So when is a plain assert right? When the value is already final and does not depend on the page changing:

  • Python values you calculated: assert total == 300.
  • An API response you already received: assert response.status == 200.
  • Values after a web-first assertion has already waited for the page to settle.

💬 Custom Messages and Timeouts

Pass a second argument to expect() to explain what failed in business terms, and timeout= (milliseconds) to change how long one assertion waits:

📄 demos/test_message.py

import pytest
from playwright.sync_api import Page, expect


@pytest.fixture
def practice(page: Page) -> Page:
    page.goto("https://sqatools.in/automation-practice-page/")
    return page


def test_ajax_within_two_seconds(practice: Page):
    practice.get_by_role("button", name="Load Success").click()

    expect(
        practice.locator("#loader"),
        "AJAX data should load within 2 seconds",
    ).to_have_text("Data loaded successfully!", timeout=2_000)

⌨️ Terminal

pytest -q demos/test_message.py

🖥️ Output

E       AssertionError: AJAX data should load within 2 seconds
E       Expected value: 'Data loaded successfully!'
E       Actual value: Loading... 
E       Call log:
E         - Expect "to_have_text" locator("#loader") with timeout 2000ms
E         - waiting for locator("#loader")
E           20 × locator resolved to <p id="loader">Loading...</p>
E              - unexpected value "Loading..."
E       
E       Aria snapshot:
E       - paragraph: Loading...

demos\test_message.py:17: AssertionError
=========================== short test summary info ===========================
FAILED demos/test_message.py::test_ajax_within_two_seconds[chromium] - Assert...
1 failed, 1 warning in 3.99s

Read the failure from top to bottom:

  • Your message comes first, then the expected and actual values.
  • The call log shows each retry: Playwright kept finding #loader with the text “Loading…” until the 2 seconds ran out.
  • The real data arrives after 3 seconds, so a 2-second limit fails. Choose timeouts from real requirements, not by guessing.

Changing the default timeout for all assertions

The default is 5 seconds. To change it for the whole suite, call expect.set_options() once, for example in conftest.py:

📄 global_timeout/conftest.py

from playwright.sync_api import expect

# Every expect(...) in this suite now waits up to 10 seconds by default
expect.set_options(timeout=10_000)

📄 global_timeout/test_slow_page.py

from playwright.sync_api import Page, expect


def test_uses_the_global_timeout(page: Page):
    page.goto("https://sqatools.in/automation-practice-page/")
    page.get_by_role("button", name="Load Success").click()
    expect(page.locator("#loader")).to_have_text("Data loaded successfully!")
  • A timeout= argument on a single assertion still overrides the global value.
  • expect.set_options() affects only assertions. Action timeouts (click, fill) are set on the page or context; you will see them in the next lesson.

🧺 Soft Assertions: Collect Failures, Keep Going

A normal assertion stops the test at the first failure. Sometimes you want to check several independent things on one page and see every problem in a single run, for example all the labels of a form. That is what expect.soft() does:

📄 demos/test_soft.py

import pytest
from playwright.sync_api import Page, expect


@pytest.fixture
def practice(page: Page) -> Page:
    page.goto("https://sqatools.in/automation-practice-page/")
    return page


def test_form_labels(practice: Page):
    # Each soft check records a failure and lets the test continue
    expect.soft(practice.locator("#submitButton")).to_have_text("Send", timeout=1_000)
    expect.soft(practice.locator("#normalButton")).to_have_text("Normal Button")
    expect.soft(practice.locator("#username")).to_have_attribute(
        "placeholder", "Your username", timeout=1_000
    )

    print("\nThe test body reached its last line")

⌨️ Terminal

pytest -q demos/test_soft.py

🖥️ Output

_________________________ test_form_labels[chromium] __________________________
  + Exception Group Traceback (most recent call last):
  |   File "C:\pwv\_venv0\Lib\site-packages\pytest_playwright\pytest_playwright.py", line 137, in pytest_runtest_call
  |     raise _BaseExceptionGroup("Soft assertion failures", errors)
  | ExceptionGroup: Soft assertion failures (2 sub-exceptions)
  +-+---------------- 1 ----------------
    | AssertionError: Locator expected to have text 'Send'
    | Actual value: Submit 
    | Call log:
    |   - Expect "to_have_text" locator("#submitButton") with timeout 1000ms
    |   - waiting for locator("#submitButton")
    |     11 × locator resolved to <button type="submit" id="submitButton">Submit</button>
    |        - unexpected value "Submit"
    | 
    | Aria snapshot:
    | - button "Submit"
    +---------------- 2 ----------------
    | AssertionError: Locator expected to have attribute 'Your username'
    | Actual value: Enter username 
    | Call log:
    |   - Expect "to_have_attribute" locator("#username") with timeout 1000ms
    |   - waiting for locator("#username")
    |     10 × locator resolved to <input type="text" id="username" name="username" placeholder="Enter username"/>
    |        - unexpected value "Enter username"
    | 
    | Aria snapshot:
    | - textbox "Enter username"
    +------------------------------------
---------------------------- Captured stdout call -----------------------------

The test body reached its last line
=========================== short test summary info ===========================
FAILED demos/test_soft.py::test_form_labels[chromium] - ExceptionGroup: Soft ...
1 failed, 1 warning in 4.47s
  • The test ran to the end (the print output appears under “Captured stdout call”), then failed with both problems reported together.
  • With two or more soft failures, pytest-playwright raises an ExceptionGroup named “Soft assertion failures”. With one, it raises that single AssertionError.
  • expect.soft() needs the pytest-playwright plugin (0.7.3 or later), which collects the failures for each test. Outside pytest-playwright, use a normal expect().

⚠️ Watch out: Use soft assertions for independent checks only. If a later step depends on an earlier check (for example, you must be logged in before checking the dashboard), use a normal expect() so the test stops at the real cause.


📚 Quick Reference

CategoryAssertions
Pageto_have_title, to_have_url
Visibilityto_be_visible, to_be_hidden, to_be_attached, to_be_in_viewport
Stateto_be_enabled, to_be_disabled, to_be_editable, to_be_checked, to_be_focused, to_be_empty
Textto_have_text, to_contain_text
Valuesto_have_value, to_have_values
Attributesto_have_attribute, to_have_id, to_have_class, to_contain_class, to_have_css, to_have_js_property
Countto_have_count
Accessibilityto_have_role, to_have_accessible_name, to_have_accessible_description, to_have_accessible_error_message
Structureto_match_aria_snapshot (covered in the visual testing lesson)
APIto_be_ok

Every assertion has a not_ version, such as not_to_be_visible(), and accepts timeout=.


🏋️ 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: After logging in to SQA Shop, assert the URL ends with #/, the account button contains “Hi, Test”, and the cart badge shows “0”, using web-first assertions.

Show answer
import re

expect(page).to_have_url(re.compile(r"#/$"))
expect(page.get_by_test_id("account-button")).to_contain_text("Hi, Test")
expect(page.get_by_test_id("cart-count")).to_have_text("0")

Exercise 2: Check three independent things on the practice page without stopping at the first failure, so all problems are reported together.

Show answer
expect.soft(page.locator("#username")).to_be_editable()
expect.soft(page.locator("#disabledInput")).to_be_disabled()
expect.soft(page.locator("#hiddenField")).to_be_hidden()

Soft assertions record failures and fail the test at the end, listing all of them.

Exercise 3: Give a custom message to an assertion so the report explains the business meaning.

Show answer
expect(page.get_by_test_id("coupon-discount"), "SAVE10 must be capped at ₹500").to_have_text("−₹500")

🧠 MCQ Quiz: Playwright Python Assertions with expect

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. What makes an assertion “web-first”?
  2. What is the default timeout of expect assertions?
  3. Which assertion checks the page title?
  4. What is the difference between to_have_text and to_contain_text?
  5. How do you assert an element is NOT visible?
  6. Which assertion checks an input’s current value?
  7. What does expect.soft(...) do?
  8. How do you check the number of matching elements?
  9. When is a plain assert fine?
  10. Which assertion checks an API response status is 2xx?

Want a longer, timed test? Take the Module 5 mock interview (20 MCQs in 20 minutes).


❓ Frequently Asked Questions

🤔 What is the difference between to_have_text and to_contain_text?

to_have_text() requires the whole text of the element to match (string or regex). to_contain_text() passes if the expected string appears anywhere in the text. Both ignore leading and trailing whitespace and retry until the timeout.

🤔 Should I write not_to_be_visible() or to_be_hidden()?

They are equivalent for a single element: both pass when the element is invisible or missing. Pick the one that reads better in your test.

🤔 Why does my assertion take 5 seconds before failing?

That is the default assertion timeout: expect keeps retrying in case the page is still updating. If 5 seconds is too long or too short, pass timeout= to that assertion or call expect.set_options(timeout=...) once.

🤔 Can I use expect with plain Python values, like numbers or lists?

No. expect() accepts a Page, a Locator or an APIResponse. For plain Python values, use pytest’s assert, which shows a detailed comparison on failure.

🤔 Is there a to_have_screenshot assertion in Python?

Not in Playwright for Python 1.64. The TypeScript test runner has one, but Python does not. The visual testing lesson in this module shows how to do screenshot comparison in Python.


🏁 Summary

  • expect() assertions retry until the page matches or the timeout (5 s by default) runs out; this removes most flaky waits.
  • Use page assertions for title and URL, and locator assertions for visibility, state, text, values, attributes, CSS and count.
  • to_have_text matches the whole text; to_contain_text a part. Lists check several elements in order.
  • Every assertion has a not_ form; add a custom message as the second argument of expect() and timeout= per check, or expect.set_options() globally.
  • expect.soft() collects independent failures and reports them together at the end of the test.
  • Use a plain assert for values that are already final, never for page content that may still be changing.

Next, you will look at the waiting side of the same coin: how Playwright’s auto-waiting works for actions, and the explicit waits you need for navigation, network responses and custom conditions.

🎬 Watch the Playwright tutorial series on YouTube!

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

File Upload and File Download in Playwright Python (set_input_files, expect_download)

Uploading a profile picture, importing a CSV, exporting a report: file transfer is part of many test flows. Playwright handles both directions without touching the operating system’s file dialogs. In this lesson you will upload real and in-memory files to the SQA Tools practice page, use the file chooser event, and capture, save and verify downloads, including files the page generates on the fly.

📖 What You’ll Learn: set_input_files with a path, several files and in-memory content, checking what was selected, clearing a file input, expect_file_chooser for upload buttons that hide the input, expect_download, suggested_filename, save_as and path, verifying the downloaded content, downloads generated by JavaScript, and where Playwright stores downloads.


📤 Uploading Files: set_input_files

A file upload on a web page is an <input type="file">. Instead of opening the operating system’s file dialog (which automation cannot control), Playwright sets the input’s files directly with set_input_files(). The practice page has one: <input type="file" id="fileUpload">.

📄 tests/conftest.py

import pytest
from playwright.sync_api import Page


@pytest.fixture
def practice(page: Page) -> Page:
    page.goto("https://sqatools.in/automation-practice-page/")
    return page

📄 tests/test_upload.py

from pathlib import Path

from playwright.sync_api import Page, expect

SELECTED_NAMES = "el => [...el.files].map(f => f.name + ' (' + f.size + ' bytes)')"


def test_upload_file_from_disk(practice: Page, tmp_path: Path):
    # Create a real file to upload (in a real project, keep test files in a test_data folder)
    report = tmp_path / "report.csv"
    report.write_text("id,name\n1,Deepesh\n")

    upload = practice.locator("#fileUpload")
    upload.set_input_files(report)

    print("\nselected:", upload.evaluate(SELECTED_NAMES))
    expect(upload).to_have_value("C:\\fakepath\\report.csv")


def test_upload_in_memory_file(practice: Page):
    upload = practice.locator("#fileUpload")
    upload.set_input_files({
        "name": "notes.txt",
        "mimeType": "text/plain",
        "buffer": b"created in memory by the test",
    })
    print("\nin memory:", upload.evaluate(SELECTED_NAMES))
    assert upload.evaluate("el => el.files[0].name") == "notes.txt"


def test_clear_selection(practice: Page, tmp_path: Path):
    file = tmp_path / "a.txt"
    file.write_text("a")
    upload = practice.locator("#fileUpload")
    upload.set_input_files(file)
    upload.set_input_files([])                     # an empty list removes the selection
    expect(upload).to_have_value("")

Line by line:

  • set_input_files(path) accepts a path as a string or pathlib.Path. Relative paths are resolved from the folder where you run pytest.
  • To see what was selected, the test reads the input’s files list in the browser with evaluate: name and size of each file.
  • Browsers never reveal the real path of an uploaded file, so the input’s value is always C:\fakepath\<name>, on every operating system. to_have_value checks exactly that.
  • Instead of a file on disk, you can pass a dictionary with name, mimeType and buffer (bytes). This is handy for generated content and avoids test-data files.
  • set_input_files([]) clears the selection.
  • For inputs with the multiple attribute, pass a list of paths to upload several files at once.

🖥️ Output

selected: ['report.csv (20 bytes)']
in memory: ['notes.txt (29 bytes)']

(The CSV is 20 bytes on Windows, where Python’s write_text stores each line break as two characters, \r\n; on Linux and macOS the same file is 18 bytes.)

📝 Note: set_input_files only selects the file, exactly like a user picking it in the dialog. Whatever the page does next (uploading on change, or on clicking an Upload button) you trigger and verify as usual.


🗂️ Upload Buttons That Hide the Input: expect_file_chooser

Many sites hide the real file input behind a styled button. Clicking the button opens the native file dialog, which Playwright intercepts as a file chooser event:

📄 tests/test_upload.py

def test_file_chooser(page: Page, tmp_path: Path):
    page.set_content("""
        <input type="file" id="hidden-input" style="display:none">
        <button onclick="document.getElementById('hidden-input').click()">Choose photo</button>
        <p id="status"></p>
        <script>
          document.getElementById('hidden-input').onchange = e =>
            document.getElementById('status').textContent = 'Selected: ' + e.target.files[0].name;
        </script>
    """)
    photo = tmp_path / "avatar.png"
    photo.write_bytes(b"\x89PNG fake image bytes")

    with page.expect_file_chooser() as chooser_info:
        page.get_by_role("button", name="Choose photo").click()
    chooser = chooser_info.value
    chooser.set_files(photo)

    expect(page.locator("#status")).to_have_text("Selected: avatar.png")
  • page.expect_file_chooser() starts waiting before the click, like expect_popup() in Lesson 34.
  • chooser.set_files(...) accepts the same arguments as set_input_files. The page’s change event fires, so the page reacts exactly as it would for a real user.
  • You could also call set_input_files directly on the hidden input; it works on hidden inputs too. The file chooser approach is useful when you do not know where the input is.

📥 Downloading Files: expect_download

When a click starts a download, wrap it in page.expect_download(). The Download object lets you read the file name, save the file and check its content:

📄 tests/test_download.py

import csv
from pathlib import Path

from playwright.sync_api import Page

PAGE = """
<a id="static" href="data:text/csv;charset=utf-8,id%2Cname%0A1%2CDeepesh%0A2%2CRahul" download="users.csv">Export users</a>
<button id="generate">Generate report</button>
<script>
  document.getElementById('generate').onclick = () => {
    const text = 'Total tests: 42\\nPassed: 40\\nFailed: 2';
    const url = URL.createObjectURL(new Blob([text], { type: 'text/plain' }));
    const a = document.createElement('a');
    a.href = url; a.download = 'summary.txt'; a.click();
  };
</script>
"""


def test_download_csv(page: Page, tmp_path: Path):
    page.set_content(PAGE)

    with page.expect_download() as download_info:
        page.get_by_role("link", name="Export users").click()
    download = download_info.value

    print("\nsuggested name:", download.suggested_filename)
    target = tmp_path / download.suggested_filename
    download.save_as(target)

    with open(target, newline="", encoding="utf-8") as f:
        rows = list(csv.DictReader(f))
    print("rows:", rows)
    assert rows == [{"id": "1", "name": "Deepesh"}, {"id": "2", "name": "Rahul"}]


def test_download_generated_by_javascript(page: Page):
    page.set_content(PAGE)

    with page.expect_download() as download_info:
        page.get_by_role("button", name="Generate report").click()
    download = download_info.value

    assert download.failure() is None              # None means the download succeeded
    content = Path(download.path()).read_text()
    print("\n" + download.suggested_filename + ":", content.splitlines())
    assert "Failed: 2" in content

Line by line:

  • page.expect_download() waits for a download that starts during the with block.
  • download.suggested_filename is the name the site proposed (from the download attribute or the server’s headers).
  • download.save_as(path) copies the file to a location you choose. Here it goes to pytest’s tmp_path, which is cleaned up automatically.
  • download.path() returns where Playwright saved the file temporarily; it waits until the download has finished. download.failure() returns None on success or an error message.
  • The second download is generated by JavaScript in the browser (a Blob turned into a temporary URL), the same technique many “Export” buttons use. Playwright captures it the same way.
  • Python’s csv.DictReader turns the CSV into a list of dictionaries, so the test checks the content, not just that a file arrived.

🖥️ Output

suggested name: users.csv
rows: [{'id': '1', 'name': 'Deepesh'}, {'id': '2', 'name': 'Rahul'}]
summary.txt: ['Total tests: 42', 'Passed: 40', 'Failed: 2']

📁 Where Do Downloads Go?

  • By default, Playwright saves downloads in a temporary folder that is deleted when the browser context closes. With pytest-playwright that happens at the end of each test, so call save_as() if you need the file afterwards.
  • Downloads are accepted by default in pytest-playwright contexts (accept_downloads=True).
  • To keep all downloads in a fixed folder, pass downloads_path in browser_type_launch_args (Lesson 6), but save_as() per test is usually clearer.

⌨️ Terminal

pytest -q -s tests

🖥️ Output

suggested name: users.csv
rows: [{'id': '1', 'name': 'Deepesh'}, {'id': '2', 'name': 'Rahul'}]
.
summary.txt: ['Total tests: 42', 'Passed: 40', 'Failed: 2']
.
selected: ['report.csv (20 bytes)']
.
in memory: ['notes.txt (29 bytes)']
...
6 passed, 1 warning in 7.86s

🏋️ 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: Upload a file created in memory (name notes.txt, content “hello”) to the practice page’s file input without writing it to disk.

Show answer
page.locator("#fileUpload").set_input_files({
    "name": "notes.txt",
    "mimeType": "text/plain",
    "buffer": b"hello",
})

Exercise 2: Clear a file input and check it is empty.

Show answer
page.locator("#fileUpload").set_input_files([])
assert page.locator("#fileUpload").evaluate("el => el.files.length") == 0

Exercise 3: Download the SQA Bank statement CSV (button test id download-csv), save it under pytest’s tmp_path, and check the first line is the header.

Show answer
def test_statement_csv(bank_page, tmp_path):
    with bank_page.expect_download() as info:
        bank_page.get_by_test_id("download-csv").click()
    path = tmp_path / info.value.suggested_filename
    info.value.save_as(path)
    assert path.read_text(encoding="utf-8").splitlines()[0].startswith('"Date"')

(bank_page is a logged-in SQA Bank page, as in Project 4.)


🧠 MCQ Quiz: File Upload and File Download

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 method uploads a file to an <input type="file">?
  2. How do you upload several files at once?
  3. How do you handle an upload button that opens a native file dialog without a visible input?
  4. Which call waits for a download?
  5. What does download.suggested_filename return?
  6. How do you keep a downloaded file?
  7. Where should tests save downloads?
  8. How do you clear a file input?
  9. Why verify the downloaded content, not only that a download happened?
  10. Can you upload a file from memory without a path?

Want a longer, timed test? Take the Module 4 mock interview (20 MCQs in 20 minutes).


❓ Frequently Asked Questions

🤔 Can Playwright click “Browse” and pick a file in the Windows dialog?

No automation tool should drive the native dialog. Playwright intercepts it instead: use set_input_files() on the input, or expect_file_chooser() around the click.

🤔 Why is the input value C:\fakepath\… on Linux too?

It is a browser security rule: the real path is never revealed to the page, on any operating system.

🤔 How do I check that the download was a valid Excel or PDF file?

Save it, then open it with a Python library: openpyxl for Excel, pypdf for PDF, csv or json for text formats. Module 7 covers reading test data files.

🤔 My download test fails with a timeout. Why?

The click did not start a download (it may open the file in a new tab instead), or the download started before the with page.expect_download() block. Start waiting first, then click inside the block.


🏁 Summary

  • set_input_files() selects files on an <input type="file">: paths, lists, in-memory buffers, or [] to clear.
  • expect_file_chooser() handles upload buttons that open the native dialog.
  • expect_download() captures downloads; use suggested_filename, save_as(), path() and failure(), then verify the content.
  • Downloads live in a temporary folder that disappears with the context, so save what you need.

That completes Module 4. Test yourself with the Module 4 mock interview, then continue to Module 5: assertions, waits and screenshots.

🎬 Watch the Playwright tutorial series on YouTube!

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

Read and Verify Web Tables with Playwright Python (Rows, Columns, Sorting, Pagination)

Tables are everywhere in business applications: orders, users, invoices, test results. Testing them means reading cells reliably, finding the right row, checking a column, verifying sort order and walking through pages. In this lesson you will build reusable helpers that turn any HTML table into Python data, use them on the SQA Tools practice table, and then test sorting and pagination on a richer table.

📖 What You’ll Learn: the structure of an HTML table and its ARIA roles, reading headers, rows and cells with locators, converting a table to a list of dictionaries, finding a row by a cell value, reading a column by header name, asserting a whole table with to_have_text, fast extraction with evaluate, checking sort order, and collecting data across paginated pages.


🧱 Table Structure and Roles

🖥️ Output

<table>
  <thead>
    <tr> <th>ID</th> <th>Name</th> <th>Role</th> </tr>          role=row with role=columnheader
  </thead>
  <tbody>
    <tr> <td>1</td> <td>Deepesh</td> <td>Trainer</td> </tr>  role=row with role=cell
    ...
  </tbody>
</table>

Playwright gives table parts ARIA roles: table, row, columnheader and cell. A row’s accessible name is its cells’ text joined with spaces, which is why get_by_role("row", name="2 Rahul Tester") works. The practice page table has 3 data rows:

IDNameRole
1DeepeshTrainer
2RahulTester
3AnitaDeveloper

🔎 Reading Headers, Rows and Cells

📄 tests/conftest.py

import pytest
from playwright.sync_api import Page


@pytest.fixture
def practice(page: Page) -> Page:
    page.goto("https://sqatools.in/automation-practice-page/")
    return page

📄 tests/test_table_basics.py

from playwright.sync_api import Page, expect


def test_read_table(practice: Page):
    table = practice.get_by_role("table")

    headers = table.get_by_role("columnheader").all_inner_texts()
    print("\nheaders:", headers)
    assert headers == ["ID", "Name", "Role"]

    rows = table.locator("tbody tr")
    expect(rows).to_have_count(3)

    # One cell: 2nd row, 2nd column (0-based)
    expect(rows.nth(1).locator("td").nth(1)).to_have_text("Rahul")

    # A whole column, checked in one assertion
    expect(rows.locator("td:nth-child(2)")).to_have_text(["Deepesh", "Rahul", "Anita"])
  • get_by_role("columnheader") finds the <th> header cells; all_inner_texts() returns their text as a list.
  • tbody tr selects only data rows, skipping the header row.
  • rows.locator("td:nth-child(2)") selects the second cell of every row; passing a list to to_have_text checks all of them in order and waits until they match. This is the most robust way to assert table content.

🗂️ Turn a Table into Python Data

Assertions on single cells get long. A small helper that converts the table into a list of dictionaries makes tests read like requirements. Put it in utils/tables.py:

📄 utils/tables.py

from playwright.sync_api import Locator


def table_to_dicts(table: Locator) -> list[dict[str, str]]:
    """Read an HTML table into [{header: cell_text, ...}, ...]."""
    headers = [h.strip() for h in table.locator("thead th").all_inner_texts()]
    data = []
    for row in table.locator("tbody tr").all():
        cells = [c.strip() for c in row.locator("td").all_inner_texts()]
        data.append(dict(zip(headers, cells)))
    return data


def column(table: Locator, header: str) -> list[str]:
    """All values of the column with this header text."""
    headers = [h.strip() for h in table.locator("thead th").all_inner_texts()]
    index = headers.index(header) + 1                 # CSS nth-child is 1-based
    return [c.strip() for c in table.locator(f"tbody tr td:nth-child({index})").all_inner_texts()]


def row_by_cell(table: Locator, text: str) -> Locator:
    """The data row that contains a cell with exactly this text."""
    return table.locator("tbody tr").filter(has=table.page.get_by_role("cell", name=text, exact=True))
  • table_to_dicts reads the headers once, then zips each row’s cells with them: dict(zip(["ID", "Name"], ["1", "Deepesh"])) gives {"ID": "1", "Name": "Deepesh"}.
  • column finds the header’s position by name, so tests keep working if a column is added or moved.
  • row_by_cell returns a locator for the row, so a test can click a button inside it or assert on it with auto-waiting.
  • .strip() removes stray whitespace that HTML often adds around cell text.

Tests using the helpers (tests/test_table_helpers.py):

📄 tests/test_table_helpers.py

from playwright.sync_api import Page, expect

from utils.tables import column, row_by_cell, table_to_dicts


def test_table_as_dicts(practice: Page):
    table = practice.get_by_role("table")
    expect(table.locator("tbody tr")).to_have_count(3)      # make sure rows are loaded first

    data = table_to_dicts(table)
    print("\n", data)
    assert data[1] == {"ID": "2", "Name": "Rahul", "Role": "Tester"}
    assert [row["Role"] for row in data] == ["Trainer", "Tester", "Developer"]


def test_column_and_row_lookup(practice: Page):
    table = practice.get_by_role("table")
    expect(table.locator("tbody tr")).to_have_count(3)

    assert column(table, "Name") == ["Deepesh", "Rahul", "Anita"]

    anita = row_by_cell(table, "Anita")
    expect(anita.locator("td").last).to_have_text("Developer")
    expect(anita.locator("td").first).to_have_text("3")

🖥️ Output

 [{'ID': '1', 'Name': 'Deepesh', 'Role': 'Trainer'}, {'ID': '2', 'Name': 'Rahul', 'Role': 'Tester'}, {'ID': '3', 'Name': 'Anita', 'Role': 'Developer'}]

⚠️ Watch out: all() and all_inner_texts() read the table immediately, without waiting. Always wait for the table to be ready first, for example with expect(rows).to_have_count(...) or expect(rows.first).to_be_visible(), or you may read a half-loaded table.


⚡ Fast Extraction with evaluate

Reading a large table cell by cell sends one request to the browser per cell. For hundreds of rows, extract everything in a single call with JavaScript running inside the page:

📄 tests/test_table_helpers.py

def test_extract_with_evaluate(practice: Page):
    table = practice.get_by_role("table")
    expect(table.locator("tbody tr")).to_have_count(3)

    rows = table.evaluate(
        "t => [...t.querySelectorAll('tbody tr')].map(r => [...r.cells].map(c => c.innerText.trim()))"
    )
    print("\nrows:", rows)
    assert rows == [["1", "Deepesh", "Trainer"], ["2", "Rahul", "Tester"], ["3", "Anita", "Developer"]]

locator.evaluate(js) runs the function with the matched element as its argument (t) and returns the result to Python as lists and strings. r.cells is the browser’s list of a row’s cells.


↕️ Sorting and Pagination

The practice table is static, so for sorting and paging we build a richer table with set_content(): 7 products, a sortable Price header and pages of 3 rows. The page logic is plain JavaScript, just like a real app.

📄 tests/product_table.py

HTML = """
<table id="products">
  <thead><tr><th>Product</th><th><button id="sort-price">Price</button></th></tr></thead>
  <tbody></tbody>
</table>
<button id="prev">Previous</button> <span id="page-info"></span> <button id="next">Next</button>
<script>
  const items = [["Backpack", 29.99], ["Bike Light", 9.99], ["Bolt T-Shirt", 15.99],
                 ["Fleece Jacket", 49.99], ["Onesie", 7.99], ["Red T-Shirt", 15.99], ["Water Bottle", 12.50]];
  let page = 0, sorted = items.slice();
  function render() {
    const rows = sorted.slice(page * 3, page * 3 + 3);
    document.querySelector("#products tbody").innerHTML =
      rows.map(([n, p]) => `<tr><td>${n}</td><td>$${p.toFixed(2)}</td></tr>`).join("");
    document.querySelector("#page-info").textContent = `Page ${page + 1} of 3`;
    document.querySelector("#prev").disabled = page === 0;
    document.querySelector("#next").disabled = page === 2;
  }
  document.querySelector("#next").onclick = () => { page++; render(); };
  document.querySelector("#prev").onclick = () => { page--; render(); };
  document.querySelector("#sort-price").onclick = () => {
    sorted.sort((a, b) => a[1] - b[1]); page = 0; render();
  };
  render();
</script>
"""

📄 tests/test_sort_and_pages.py

from playwright.sync_api import Page, expect

from tests.product_table import HTML


def prices_on_page(page: Page) -> list[float]:
    texts = page.locator("#products tbody td:nth-child(2)").all_inner_texts()
    return [float(t.replace("$", "")) for t in texts]


def test_sort_by_price(page: Page):
    page.set_content(HTML)
    page.get_by_role("button", name="Price").click()

    expect(page.locator("#products tbody tr").first).to_contain_text("Onesie")   # wait for re-render
    prices = prices_on_page(page)
    print("\nfirst page after sort:", prices)
    assert prices == sorted(prices)


def test_collect_all_pages(page: Page):
    page.set_content(HTML)
    names = []

    while True:
        expect(page.locator("#products tbody tr").first).to_be_visible()
        names += page.locator("#products tbody td:nth-child(1)").all_inner_texts()
        next_button = page.get_by_role("button", name="Next")
        if next_button.is_disabled():
            break
        info = page.locator("#page-info").inner_text()
        next_button.click()
        expect(page.locator("#page-info")).not_to_have_text(info)   # wait until the page changed

    print("all products:", names)
    assert len(names) == 7
    expect(page.locator("#page-info")).to_have_text("Page 3 of 3")

What the tests do:

  • Sorting: click the header, wait until the table re-rendered (the cheapest item, Onesie, is now first), read the prices, and compare them with Python’s sorted() version of the same list.
  • Pagination: loop: read the current page, stop when Next is disabled, otherwise remember the page label, click Next, and wait until the label changes before reading again. Waiting for a visible change is what makes the loop reliable; reading immediately after the click could read the old page twice.
  • is_disabled() returns the button’s state right now; inside the loop the page has already been confirmed as updated, so that is safe.

⌨️ Terminal

pytest -q -s tests

🖥️ Output

first page after sort: [7.99, 9.99, 12.5]
.all products: ['Backpack', 'Bike Light', 'Bolt T-Shirt', 'Fleece Jacket', 'Onesie', 'Red T-Shirt', 'Water Bottle']
.
headers: ['ID', 'Name', 'Role']
.
 [{'ID': '1', 'Name': 'Deepesh', 'Role': 'Trainer'}, {'ID': '2', 'Name': 'Rahul', 'Role': 'Tester'}, {'ID': '3', 'Name': 'Anita', 'Role': 'Developer'}]
..
rows: [['1', 'Deepesh', 'Trainer'], ['2', 'Rahul', 'Tester'], ['3', 'Anita', 'Developer']]
.
6 passed, 1 warning in 10.08s

The pagination loop collected all 7 products across 3 pages, each exactly once.


🏋️ 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: Convert the web table on the automation practice page into a list of dictionaries keyed by the header names.

Show answer
table = page.locator("table").first
headers = table.locator("th").all_inner_texts()
rows = []
for row in table.locator("tbody tr").all():
    cells = row.locator("td").all_inner_texts()
    rows.append(dict(zip(headers, cells)))
print(rows)

Exercise 2: Find the row whose Name is “Rahul” and read its Role, using role-based locators.

Show answer
row = page.get_by_role("row").filter(has=page.get_by_role("cell", name="Rahul", exact=True))
print(row.get_by_role("cell").nth(2).inner_text())

Exercise 3: Assert that the Name column is sorted alphabetically.

Show answer
names = [r["Name"] for r in rows]          # from the list of dictionaries above
assert names == sorted(names), names

For a single retrying assertion on a known order use expect(locator).to_have_text([...]).


🧠 MCQ Quiz: Read Data from Web Tables

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 ARIA role does a table row have?
  2. How do you get all header texts of a table?
  3. Why zip headers with cells?
  4. How do you find a row containing a specific value?
  5. What does expect(rows).to_have_count(5) check?
  6. Why might reading a large table with page.evaluate be faster?
  7. How do you assert the whole first column in one step?
  8. What is a reliable way to collect data across a paginated table?
  9. Which locator method returns a list of row locators?
  10. Why check sort order in code rather than by eye?

Want a longer, timed test? Take the Module 4 mock interview (20 MCQs in 20 minutes).


❓ Frequently Asked Questions

🤔 Should I read tables with locators or with evaluate?

Use locators and expect(...).to_have_text([...]) for assertions, because they wait and retry. Use evaluate to extract large amounts of data quickly once the table is loaded.

🤔 How do I click a button in a specific row?

Find the row first, then search inside it: row_by_cell(table, "Anita").get_by_role("button", name="Edit").click().

🤔 My table has no thead. How do I find the headers?

Use the first row: table.locator("tr").first.locator("th, td").all_inner_texts(), and read data rows with table.locator("tr").nth(i) starting at 1.

🤔 How do I verify that a table is sorted by a date column?

Read the column, convert each text to a datetime with datetime.strptime(text, "%d/%m/%Y"), then compare the list with sorted(...) of itself.


🏁 Summary

  • Tables expose row, columnheader and cell roles; tbody tr selects data rows.
  • Assert columns with to_have_text([...]); convert tables to lists of dicts with small helpers; find rows by cell value and columns by header name.
  • locator.evaluate() extracts large tables in one call; always wait for the table before reading.
  • For sorting, compare the read list with sorted(); for pagination, wait for a visible page change before reading each page.

Next, you will upload and download files.

🎬 Watch the Playwright tutorial series on YouTube!

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

Playwright Python: Handle Alerts, Confirm and Prompt Dialogs, iFrames, Popups and New Tabs

Real applications do not stay on one page. They show alert and confirm dialogs, embed content in iframes, and open links in new tabs. Each needs a slightly different technique in Playwright. In this lesson you will handle all three kinds of JavaScript dialogs, find elements inside iframes (including the lazy-loaded iframe on the SQA Tools practice page), and open, switch between and close tabs and popups.

📖 What You’ll Learn: how Playwright treats dialogs by default, page.on and page.once dialog handlers, dialog.type, message, default_value, accept and dismiss, answering a prompt, frame_locator and content_frame, nested frames, the Frame API, lazy-loaded iframes, expect_popup and context.expect_page, listing and switching tabs, and closing pages.


💬 JavaScript Dialogs: alert, confirm and prompt

The practice page has three buttons that open the three kinds of native browser dialogs:

ButtonJavaScriptDialog typeUser can
Simple Alertalert("This is a simple alert!")alertClick OK
Confirm Alertconfirm("Do you want to continue?")confirmOK or Cancel
Prompt Alertprompt("Enter your name:")promptType text, then OK or Cancel

The default: dialogs are dismissed automatically

If your test has no dialog handler, Playwright automatically dismisses every dialog, so the test never hangs. For an alert that is harmless; for a confirm it means “Cancel”. The first test proves that clicking “Simple Alert” without a handler does not block anything.

Handling dialogs with page.on / page.once

To inspect or answer a dialog, register a handler before the action that opens it:

📄 tests/conftest.py

import pytest
from playwright.sync_api import Page


@pytest.fixture
def practice(page: Page) -> Page:
    page.goto("https://sqatools.in/automation-practice-page/")
    return page

📄 tests/test_dialogs.py

from playwright.sync_api import Dialog, Page, expect


def test_alert_without_handler_is_dismissed(practice: Page):
    practice.get_by_role("button", name="Simple Alert").click()
    # The test continues: Playwright dismissed the alert automatically
    expect(practice.get_by_role("button", name="Simple Alert")).to_be_visible()


def test_read_and_accept_alert(practice: Page):
    messages = []

    def handle(dialog: Dialog):
        messages.append((dialog.type, dialog.message))
        dialog.accept()

    practice.once("dialog", handle)                       # handle only the next dialog
    practice.get_by_role("button", name="Simple Alert").click()
    print("\nalert:", messages)
    assert messages == [("alert", "This is a simple alert!")]


def test_confirm_ok_and_cancel(practice: Page):
    seen = []
    practice.once("dialog", lambda d: (seen.append(d.message), d.accept()))    # OK
    practice.get_by_role("button", name="Confirm Alert").click()
    practice.once("dialog", lambda d: (seen.append(d.type), d.dismiss()))      # Cancel
    practice.get_by_role("button", name="Confirm Alert").click()
    assert seen == ["Do you want to continue?", "confirm"]


def test_answer_prompt(practice: Page):
    answer = {}

    def handle(dialog: Dialog):
        answer["type"] = dialog.type
        answer["default"] = dialog.default_value
        dialog.accept("Deepesh")                           # type text and press OK

    practice.once("dialog", handle)
    # The page discards the answer, so we call prompt() ourselves to see what it returns
    result = practice.evaluate("() => prompt('Enter your name:')")
    print("\nprompt:", answer, "->", result)
    assert result == "Deepesh"

Line by line:

  • page.once("dialog", handler) calls the handler for the next dialog only; page.on("dialog", handler) calls it for every dialog until you remove it with page.remove_listener("dialog", handler).
  • The handler receives a Dialog object: dialog.type (“alert”, “confirm”, “prompt” or “beforeunload”), dialog.message, and for prompts dialog.default_value.
  • dialog.accept() clicks OK; dialog.accept("text") also types the answer into a prompt; dialog.dismiss() clicks Cancel.
  • Your handler must call accept() or dismiss(). If it does neither, the dialog stays open and the page is stuck, so the click never completes.
  • The practice page’s showPrompt() throws the answer away, so the last test calls prompt() through page.evaluate() to show the value the page would receive.

🖥️ Output

alert: [('alert', 'This is a simple alert!')]
prompt: {'type': 'prompt', 'default': ''} -> Deepesh

🪟 iFrames

An iframe embeds a separate HTML document inside the page. Elements inside it are invisible to normal page locators; you must enter the frame first with frame_locator() (or content_frame on a locator pointing at the iframe).

A self-contained example

page.set_content() with the srcdoc attribute builds a page with an iframe, so the example works offline and never changes:

📄 tests/test_frames.py

from playwright.sync_api import Page, expect

HTML = """
<h1>Main page</h1>
<iframe id="payment" srcdoc="
    <h2>Card details</h2>
    <label>Card number <input id='card'></label>
    <iframe id='inner' srcdoc='<button>Pay now</button>'></iframe>
"></iframe>
"""


def test_frame_locator(page: Page):
    page.set_content(HTML)

    # A normal page locator cannot see inside the iframe
    expect(page.locator("#card")).to_have_count(0)

    # frame_locator() enters the iframe; then use any locator inside it
    payment = page.frame_locator("#payment")
    payment.get_by_label("Card number").fill("4111 1111 1111 1111")
    expect(payment.get_by_label("Card number")).to_have_value("4111 1111 1111 1111")

    # Nested iframe: chain frame_locator calls
    expect(payment.frame_locator("#inner").get_by_role("button", name="Pay now")).to_be_visible()

    # content_frame turns a locator for the <iframe> element into a frame locator
    expect(page.locator("#payment").content_frame.get_by_role("heading")).to_have_text("Card details")
  • page.frame_locator("#payment") takes a selector for the <iframe> element and returns a FrameLocator. Locators created from it search inside that frame.
  • Frames inside frames are reached by chaining frame_locator() again.
  • locator("#payment").content_frame does the same from a normal locator, which is useful when you already have one.
  • Auto-waiting works inside frames too: Playwright waits for the frame and the element to be ready.

The practice page’s lazy-loaded iframe

The iframe on the practice page is lazy-loaded: a performance plugin on the site starts it as about:blank and only loads the real page (https://example.com) when the iframe scrolls into view. A test must scroll to it first:

📄 tests/test_frames.py

def test_practice_page_iframe(page: Page):
    page.goto("https://sqatools.in/automation-practice-page/")
    iframe = page.locator("#sampleIframe")

    iframe.scroll_into_view_if_needed()                 # triggers the lazy loading
    expect(iframe).to_have_attribute("src", "https://example.com")

    frame = page.frame_locator("#sampleIframe")
    expect(frame.get_by_text("This domain is for use in documentation examples")).to_be_visible()


def test_frame_objects(page: Page):
    page.set_content(HTML)
    names = [f.name for f in page.frames]
    print("\nframes:", names)
    payment = page.frame(name="payment")
    assert payment is not None and payment.parent_frame == page.main_frame
  • The lazy loading is real-world behaviour worth knowing: if an element inside an iframe “never appears”, check whether the iframe has loaded at all (src and the network tab in the Trace Viewer).
  • page.frames lists every frame, starting with the main frame. page.frame(name=...) or page.frame(url=...) returns a Frame object, an older, lower-level API. Prefer frame_locator() for test steps, because it auto-waits and re-resolves the frame.

🗂️ Popups and New Tabs

A link with target="_blank" or a window.open() call opens a new page. Start waiting for it before the click with page.expect_popup():

📄 tests/test_tabs.py

import re

from playwright.sync_api import BrowserContext, Page, expect


def test_new_tab_with_expect_popup(page: Page):
    page.goto("https://sqatools.in/automation-practice-page/")

    with page.expect_popup() as popup_info:
        page.get_by_role("link", name="Dummy Page").click()
    new_tab = popup_info.value
    new_tab.wait_for_load_state()

    expect(new_tab).to_have_url(re.compile(r"dummy-booking-website"))
    print("\nnew tab title:", new_tab.title())

    # Switch back and forth simply by using the right Page object
    expect(page).to_have_url("https://sqatools.in/automation-practice-page/")
    new_tab.close()
    expect(page.get_by_role("link", name="Dummy Page")).to_be_visible()


def test_tabs_in_context(page: Page, context: BrowserContext):
    page.goto("https://sqatools.in/automation-practice-page/")

    with context.expect_page() as new_page_info:
        page.get_by_role("link", name="Login Page").first.click()
    login_tab = new_page_info.value

    login_tab.wait_for_load_state()
    print("\npages open:", len(context.pages), [p.url for p in context.pages])
    expect(login_tab.get_by_role("button", name="Log in")).to_be_visible()

    login_tab.bring_to_front()                         # make it the active tab (visible in headed mode)
    login_tab.close()
    assert len(context.pages) == 1
  • page.expect_popup() waits for a popup opened by that page; context.expect_page() waits for any new page in the context. Both return the new Page in .value.
  • wait_for_load_state() waits until the new tab has loaded (the load event by default).
  • There is no “switch to” command: each tab is its own Page object, and you simply call methods on the one you want. bring_to_front() only changes which tab is visible in headed mode.
  • context.pages lists all open pages in the context; closing a page removes it.
  • The practice page has two “Login Page” links, so .first picks the one at the top (strictness, Lesson 31).

⌨️ Terminal

pytest -q -s tests

🖥️ Output

.
alert: [('alert', 'This is a simple alert!')]
..
prompt: {'type': 'prompt', 'default': ''} -> Deepesh
...
frames: ['', 'payment', 'inner']
.
new tab title: Dummy Booking Website - SQA Tools
.
pages open: 2 ['https://sqatools.in/automation-practice-page/', 'https://sqatools.in/login-page/']
.
9 passed, 1 warning in 17.59s

The main frame has an empty name (''); the two iframes are named after their id attributes.


🏋️ 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: Accept a JavaScript prompt with the answer “Playwright” and print the prompt’s message, using a one-time handler.

Show answer
def answer(dialog):
    print(dialog.type, dialog.message)
    dialog.accept("Playwright")

page.once("dialog", answer)
page.get_by_role("button", name="Prompt Alert").click()

page.once handles only the next dialog, so later dialogs are not affected.

Exercise 2: Print the first 100 characters of the text inside the iframe #sampleIframe on the practice page.

Show answer
frame = page.frame_locator("#sampleIframe")
print(frame.locator("body").inner_text()[:100])

page.locator("#sampleIframe").content_frame returns the same frame locator.

Exercise 3: Click a link that opens a new tab, wait for the new page, check its title and close it.

Show answer
with page.context.expect_page() as info:
    page.locator("a[target=_blank]").first.click()          # a link that opens a new tab
new_tab = info.value
new_tab.wait_for_load_state()
print(new_tab.title())
new_tab.close()

page.expect_popup() works the same for pop-ups opened by this page.


🧠 MCQ Quiz: Dialogs, iFrames, Popups and New Tabs

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. What does Playwright do with dialogs when no handler is registered?
  2. Which property tells you whether a dialog is an alert, confirm or prompt?
  3. How do you answer a prompt?
  4. When must the dialog handler be registered?
  5. How do you work inside an iframe?
  6. How do you handle nested iframes?
  7. Which call waits for a pop-up opened by the page?
  8. How do you list all open tabs in a context?
  9. How do you bring a tab to the front?
  10. What is the difference between page.on("dialog") and page.once("dialog")?

Want a longer, timed test? Take the Module 4 mock interview (20 MCQs in 20 minutes).


❓ Frequently Asked Questions

🤔 My test hangs after clicking a button that opens an alert. Why?

Your dialog handler neither accepted nor dismissed the dialog. Every handler must call dialog.accept() or dialog.dismiss(). Without any handler, Playwright dismisses dialogs for you.

🤔 Why can’t Playwright find an element that I can see on screen?

It is probably inside an iframe. Use page.frame_locator(...) (or content_frame) to enter the frame first, and check whether the iframe has loaded.

🤔 How do I handle a “Leave site?” (beforeunload) dialog?

It arrives as a dialog with type == "beforeunload", but only when you close the page with page.close(run_before_unload=True). Handle it like any other dialog.

🤔 Can I test new tabs in Firefox and WebKit too?

Yes. Popups, tabs, dialogs and frames work the same in all three engines; run with --browser firefox --browser webkit.


🏁 Summary

  • Without a handler, Playwright dismisses dialogs; register page.once("dialog", ...) or page.on(...) before the action to read, accept (optionally with prompt text) or dismiss them.
  • Use frame_locator() (or content_frame) to work inside iframes, chain it for nested frames, and remember that iframes may be lazy-loaded.
  • Wrap clicks that open tabs in page.expect_popup() or context.expect_page(); each tab is a separate Page object.

Next, you will read and verify data in web tables.

🎬 Watch the Playwright tutorial series on YouTube!

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

Playwright Python Actions: click, fill, press, check, select_option, hover and drag_to

Locators find elements; actions use them. Playwright’s actions behave like a real user: they scroll the element into view, wait until it is ready, and then click, type or drag. In this lesson you will perform every common action on the SQA Tools practice page, learn the difference between fill and typing key by key, handle dropdowns, date fields, hover and drag and drop, and understand the actionability checks that make actions reliable.

📖 What You’ll Learn: click, double click, right click and modifier keys, fill, clear and press_sequentially, keyboard keys and shortcuts with press, check, uncheck and set_checked, select_option by value, label, index and multiple values, date and time inputs, hover, drag_to, focus and scrolling, the page.mouse and page.keyboard APIs, actionability checks, force and trial, and reading the “element is not enabled” error.


⚙️ What Happens When You Call an Action

Before any action, Playwright performs actionability checks and waits until they pass (up to the action timeout, 30 seconds by default):

CheckMeans
AttachedThe element is in the page
VisibleIt has a size and is not hidden
StableIt is not moving (for example, not animating)
Receives eventsNo other element (such as an overlay) covers it
EnabledIt is not disabled
EditableFor fill: it is not read-only

Then it scrolls the element into view and performs the action with real mouse and keyboard events. This is why Playwright tests rarely need waits.

Every example below uses this fixture to open the practice page:

📄 tests/conftest.py

import pytest
from playwright.sync_api import Page


@pytest.fixture
def practice(page: Page) -> Page:
    page.goto("https://sqatools.in/automation-practice-page/")
    return page

⌨️ Typing: fill, clear and press_sequentially

📄 tests/test_typing.py

from playwright.sync_api import Page, expect


def test_fill_and_clear(practice: Page):
    username = practice.get_by_placeholder("Enter username")

    username.fill("qa_learner")                 # replaces any existing text
    expect(username).to_have_value("qa_learner")

    username.fill("second_value")               # fill always replaces, never appends
    expect(username).to_have_value("second_value")

    username.clear()                            # empty the field
    expect(username).to_have_value("")

    # Multi-line text in a <textarea>
    address = practice.locator("#address")
    address.fill("Line 1\nLine 2")
    expect(address).to_have_value("Line 1\nLine 2")


def test_type_key_by_key(practice: Page):
    search = practice.get_by_placeholder("Search...")

    # The page shows suggestions on every key press (onkeyup), so fill() is not enough
    search.press_sequentially("pla", delay=100)
    expect(practice.locator("#suggestions div")).to_have_text(["Playwright"])

    practice.locator("#suggestions div").first.click()
    expect(search).to_have_value("Playwright")
  • fill(text) sets the value in one step and fires an input event. It is fast and right for most fields.
  • press_sequentially(text, delay=100) types one character at a time, firing key events for each, with an optional delay in milliseconds. Use it when the page reacts to individual key presses, such as this autocomplete box, which only listens for keyup events.
  • to_have_text([...]) with a list checks the texts of all matched elements, in order: exactly one suggestion, “Playwright”.

🎹 Keyboard Keys and Shortcuts: press

📄 tests/test_typing.py

def test_press_keys(practice: Page):
    key_box = practice.get_by_placeholder("Press any key")
    key_box.press("Enter")
    expect(practice.locator("#keyOutput")).to_have_text("Key Pressed: Enter")

    username = practice.get_by_placeholder("Enter username")
    username.fill("delete me")
    username.press("Control+A")                 # select all
    username.press("Backspace")                 # delete the selection
    expect(username).to_have_value("")
  • press(key) presses one key or a combination. Key names include Enter, Tab, Escape, Backspace, Delete, ArrowDown, PageDown, Home, F1 to F12, and single characters such as a.
  • Combine keys with +: Control+A, Shift+Tab. ControlOrMeta+A uses Control on Windows and Linux and Command on macOS, which is handy for cross-platform shortcuts.

🖱️ Clicking

📄 tests/test_clicks.py

from playwright.sync_api import Page, expect


def test_click_variants(practice: Page):
    button = practice.get_by_role("button", name="Normal Button")

    button.click()                              # left click
    button.dblclick()                           # double click
    button.click(button="right")                # right click (context menu)
    button.click(modifiers=["Shift"])           # Shift + click
    button.click(position={"x": 5, "y": 5})     # click at an offset inside the element
    expect(button).to_be_visible()


def test_link_inside_page(practice: Page):
    practice.get_by_role("link", name="Go to Bottom").click()
    expect(practice).to_have_url("https://sqatools.in/automation-practice-page/#bottom")
  • click() takes options: button= (“left”, “right”, “middle”), click_count=, modifiers= ([“Shift”], [“Control”], [“Alt”], [“Meta”]), position= and timeout=.
  • dblclick() is a double click.
  • Clicking the “Go to Bottom” link (href="#bottom") changes the URL fragment, which to_have_url verifies.

☑️ Checkboxes, Radios and Dropdowns

📄 tests/test_forms.py

from playwright.sync_api import Page, expect


def test_checkboxes_and_radios(practice: Page):
    java = practice.get_by_role("checkbox", name="Java")
    java.check()
    expect(java).to_be_checked()
    java.uncheck()
    expect(java).not_to_be_checked()
    java.set_checked(True)                      # handy when the state comes from test data
    expect(java).to_be_checked()

    practice.get_by_role("radio", name="Other").check()
    expect(practice.get_by_role("radio", name="Other")).to_be_checked()


def test_dropdowns(practice: Page):
    country = practice.locator("#country")

    print("\nby value:", country.select_option("usa"))
    expect(country).to_have_value("usa")

    print("by label:", country.select_option(label="UK"))
    print("by index:", country.select_option(index=1))
    expect(country).to_have_value("india")

    skills = practice.locator("#skills")         # <select multiple>
    print("multiple:", skills.select_option(["Python", "Playwright"]))
    expect(skills).to_have_values(["Python", "Playwright"])
  • check() / uncheck() set the state and verify it changed; clicking an already checked checkbox with check() does nothing, which keeps tests predictable.
  • set_checked(True/False) picks the state from a value.
  • select_option(value) matches an option by its value or its label. Use label= or index= to be explicit. It returns the list of selected values, which the test prints.
  • For a <select multiple>, pass a list; to_have_values([...]) checks all selected values.

🖥️ Output

by value: ['usa']
by label: ['uk']
by index: ['india']
multiple: ['Python', 'Playwright']

📅 Date and Time Inputs

Native date and time pickers are just inputs with a fixed value format, so use fill() with that format instead of clicking through a calendar:

📄 tests/test_forms.py

def test_date_and_time(practice: Page):
    practice.locator("#datePicker").fill("2026-11-01")              # YYYY-MM-DD
    practice.locator("#timePicker").fill("13:45")                   # HH:MM (24-hour)
    practice.locator("#dateTimePicker").fill("2026-11-01T09:30")    # YYYY-MM-DDTHH:MM

    expect(practice.locator("#datePicker")).to_have_value("2026-11-01")
    expect(practice.locator("#timePicker")).to_have_value("13:45")
    expect(practice.locator("#dateTimePicker")).to_have_value("2026-11-01T09:30")

The browser displays the date in the user’s local format, but the input’s value always uses this ISO-style format. Custom JavaScript date pickers (not native inputs) are different: you click their buttons like any other element.


🖐️ Hover, Drag and Drop, Focus and Scroll

📄 tests/test_mouse.py

from playwright.sync_api import Page, expect


def test_hover(practice: Page):
    button = practice.get_by_role("button", name="Hover Over Me")
    button.hover()
    expect(button).to_have_attribute("title", "Hover text")   # the tooltip text


def test_drag_and_drop(practice: Page):
    source = practice.locator("#drag1")
    target = practice.locator(".drop")
    source.drag_to(target)
    expect(target.locator("#drag1")).to_be_visible()          # the box is now inside the target


def test_focus_and_scroll(practice: Page):
    bottom = practice.get_by_role("heading", name="Bottom of Page")
    bottom.scroll_into_view_if_needed()
    expect(bottom).to_be_in_viewport()

    username = practice.get_by_placeholder("Enter username")
    username.focus()
    expect(username).to_be_focused()
  • hover() moves the mouse over the element, which triggers CSS :hover styles and menus that open on hover. The practice button only shows a browser tooltip from its title attribute, so the test checks that attribute.
  • drag_to(target) presses the mouse on the source, moves it to the target and releases it. After the drop, the page moved the box into the drop zone, so the chained locator target.locator("#drag1") finds it there.
  • Actions scroll automatically; scroll_into_view_if_needed() is for when you only want to bring something into view, and to_be_in_viewport() checks that it is visible on screen.
  • focus() puts the keyboard focus on an element; to_be_focused() checks it.

Low-level mouse and keyboard

For drawing, sliders or custom gestures, page.mouse and page.keyboard give raw control: page.mouse.move(x, y), page.mouse.down(), page.mouse.up(), page.mouse.wheel(0, 500), page.keyboard.type("text"), page.keyboard.press("Tab"). Prefer locator actions whenever possible, because they include the actionability checks.


🚫 When an Action Cannot Happen

The practice page has a disabled input. Trying to fill it waits for the “enabled” check and then times out:

📄 tests/test_mouse.py

import pytest
from playwright.sync_api import TimeoutError as PlaywrightTimeoutError


def test_disabled_field(practice: Page):
    disabled = practice.locator("#disabledInput")
    expect(disabled).to_be_disabled()
    with pytest.raises(PlaywrightTimeoutError) as info:
        disabled.fill("x", timeout=2000)
    print("\n" + str(info.value))

🖥️ Output

Locator.fill: Timeout 2000ms exceeded.
Call log:
  - waiting for locator("#disabledInput")
    - locator resolved to <input disabled type="text" value="Disabled" id="disabledInput"/>
    - fill("x")
  - attempting fill action
    2 × waiting for element to be visible, enabled and editable
      - element is not enabled
    - retrying fill action
    - waiting 20ms
    2 × waiting for element to be visible, enabled and editable
      - element is not enabled
    - retrying fill action
      - waiting 100ms
    ...

Playwright kept retrying with growing pauses (20 ms, 100 ms, 500 ms…) until the 2-second timeout ran out. The call log tells you exactly which check failed: element is not enabled. When a real test times out, this is the first place to look: “not visible”, “not stable” or “element intercepts pointer events” (something is covering it) each point to a different cause.

force and trial

  • click(force=True) skips the actionability checks. Use it only when you are sure the check is wrong for your case; it can hide real bugs such as a button covered by a popup.
  • click(trial=True) performs the checks without clicking, which is a way to wait until an element is actionable.

▶️ Run Everything

⌨️ Terminal

pytest -q -s tests

🖥️ Output

12 passed, 1 warning in 28.29s

🏋️ 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: On the automation practice page, fill the username, select “India” in the country dropdown, tick the Python checkbox and choose the “female” radio button.

Show answer
page.locator("#username").fill("demo")
page.locator("#country").select_option(label="India")
page.get_by_label("Python").check()
page.locator("#female").check()

Exercise 2: Select two options (“Python” and “Playwright”) in the multi-select #skills and assert both are selected.

Show answer
page.locator("#skills").select_option(["Python", "Playwright"])
expect(page.locator("#skills")).to_have_values(["Python", "Playwright"])

(select_option matches values or labels; to_have_values checks the selected values.)

Exercise 3: Type “playwright” into the search box one key at a time with a 100 ms delay, then press Enter.

Show answer
search = page.locator("#searchBox")
search.press_sequentially("playwright", delay=100)
search.press("Enter")

press_sequentially triggers key events for each character, which autocomplete widgets need.


🧠 MCQ Quiz: Actions: click, fill, press, check, select_option

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 method sets an input’s value in one step?
  2. How do you right-click an element?
  3. How do you click with the Shift key held?
  4. Which method sets a checkbox to a given state?
  5. How do you select a dropdown option by its visible text?
  6. How do you fill a date input?
  7. Which method drags one element onto another?
  8. What are actionability checks?
  9. What does force=True do on click?
  10. What does trial=True do?

Want a longer, timed test? Take the Module 4 mock interview (20 MCQs in 20 minutes).


❓ Frequently Asked Questions

🤔 fill or press_sequentially?

Use fill() by default; it is faster and reliable. Use press_sequentially() only when the page reacts to individual key events, such as autocomplete, input masks or character counters.

🤔 Why did my click “time out” although the button is visible?

Read the call log: usually another element intercepts the click (a cookie banner, a loading overlay) or the button is disabled or still animating. Fix the cause rather than using force=True.

🤔 How do I select an option whose value I do not know?

Use select_option(label="Visible text"), or index= if the order is fixed.

🤔 Is type() still available?

locator.type() is deprecated. Use fill() or, for key-by-key typing, press_sequentially().


🏁 Summary

  • Actions wait for actionability (attached, visible, stable, receives events, enabled, editable) and act like real users.
  • fill replaces text; press_sequentially types key by key; press handles keys and shortcuts.
  • check, uncheck, set_checked and select_option (value, label, index, multiple) cover form controls; date inputs take ISO-style values.
  • hover, drag_to, focus and scrolling cover the rest; the call log explains any action that cannot happen.

Next, you will handle JavaScript dialogs, iframes, popups and new tabs.

🎬 Watch the Playwright tutorial series on YouTube!

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

CSS and XPath Selectors in Playwright Python (with Playwright Pseudo-classes)

The get_by_* locators cover most needs, but sometimes you need a CSS or XPath selector: an element with no accessible name, a structure-based relationship, or an existing Selenium suite you are migrating. page.locator() accepts both. In this lesson you will write CSS selectors from simple to advanced, use Playwright’s extra pseudo-classes, write XPath with axes, and learn the trade-offs that decide which to use.

📖 What You’ll Learn: page.locator with CSS and XPath, CSS ids, classes, attributes and attribute operators, descendant and child combinators, :nth-child and :checked, Playwright’s :has-text, :text, :has and :visible pseudo-classes, XPath paths, predicates, text() and contains(), axes such as following-sibling and ancestor, explicit css= and xpath= prefixes, and a checklist for choosing selectors.


🧭 page.locator(): CSS or XPath

page.locator(selector) accepts a CSS selector or an XPath expression and returns a normal Locator, with the same auto-waiting, strictness and filtering as the get_by_* locators:

  • A selector starting with // or .. is treated as XPath.
  • Everything else is treated as CSS (Playwright also understands a few extra pseudo-classes, shown below).
  • You can be explicit with a prefix: css=... or xpath=....

All examples in this lesson run on the SQA Tools practice page. Each test receives the opened page from this fixture:

📄 tests/conftest.py

import pytest
from playwright.sync_api import Page


@pytest.fixture
def practice(page: Page) -> Page:
    page.goto("https://sqatools.in/automation-practice-page/")
    return page

🎨 CSS Selectors from Simple to Advanced

📄 tests/test_css.py

from playwright.sync_api import Page, expect


def test_css_basics(practice: Page):
    # By id: #id
    practice.locator("#username").fill("qa_learner")

    # By tag + attribute: tag[attr='value']
    practice.locator("input[name='password']").fill("Secret@123")

    # By class: .class  (the drag box has class "drag")
    expect(practice.locator(".drag")).to_contain_text("Drag Me")

    # Attribute only, and tag + id
    expect(practice.locator("[placeholder='Search...']")).to_be_visible()
    expect(practice.locator("select#country")).to_have_value("")

    # Several attributes at once
    expect(practice.locator("input[type='radio'][value='female']")).to_have_id("female")
PatternMeaningExample
#idElement with this id#username
.classElement with this class.drag
tagElements of this tagselect
[attr]Has the attribute[disabled]
[attr='v']Attribute equals[name='password']
tag#id, tag.classCombinedselect#country
  • to_contain_text("Drag Me") is used instead of to_have_text on purpose: on the live site, an advertising script inserts a “Try Cloud Tools” link inside the drag box, so its full text is not just “Drag Me”. Real pages often contain injected content; check for the text that matters to your test.
  • The empty value of select#country is the “–Select Country–” placeholder option, which has value="".
  • to_have_id() checks the element’s id attribute.

Attribute operators

📄 tests/test_css.py

def test_css_attribute_operators(practice: Page):
    # ^= starts with, $= ends with, *= contains
    expect(practice.locator("a[href^='https://www.google']")).to_have_id("googleLink")
    expect(practice.locator("input[id$='Picker']")).to_have_count(3)     # date, time, datetime
    expect(practice.locator("input[placeholder*='username']")).to_have_count(1)
OperatorMeaning
[attr^='x']Value starts with x
[attr$='x']Value ends with x
[attr*='x']Value contains x

Relationships: descendant, child, sibling and position

📄 tests/test_css.py

def test_css_relationships(practice: Page):
    # Descendant (space): any depth.   Child (>): direct children only.
    expect(practice.locator("table tbody tr")).to_have_count(3)
    expect(practice.locator("table > tbody > tr > td")).to_have_count(9)

    # :nth-child(n) is 1-based: the 2nd row, 2nd cell
    expect(practice.locator("table tbody tr:nth-child(2) td:nth-child(2)")).to_have_text("Rahul")

    # Adjacent sibling (+): the label right after the Python checkbox
    expect(practice.locator("#python + label")).to_have_text("Python")

    # State pseudo-classes: :checked, :disabled
    practice.locator("#java").check()
    expect(practice.locator("input[type='checkbox']:checked")).to_have_count(1)
    expect(practice.locator("input:disabled")).to_have_id("disabledInput")
  • A space means descendant (inside, at any depth); > means direct child.
  • :nth-child(2) counts from 1 in CSS, unlike Playwright’s nth(), which counts from 0.
  • + selects the element immediately after another one at the same level.
  • :checked and :disabled select elements by their current state.

✨ Playwright’s Extra Pseudo-classes

Playwright adds pseudo-classes that plain CSS does not have:

📄 tests/test_css.py

def test_playwright_pseudo_classes(practice: Page):
    # :has-text("...") - element whose text contains the string (case-insensitive)
    expect(practice.locator("tr:has-text('Rahul')")).to_contain_text("Tester")

    # :text("...") - the smallest element containing the text
    expect(practice.locator("td:text('Anita')")).to_have_count(1)

    # :has(selector) - element containing a matching element (standard CSS in modern browsers)
    expect(practice.locator("tr:has(td:text-is('Developer'))")).to_contain_text("Anita")

    # :visible - only visible elements
    expect(practice.locator("input[type='text']:visible")).to_have_count(6)
  • :has-text("x") matches any element whose text contains x, including parents; combine it with a tag (tr:has-text(...)) to avoid matching the whole page.
  • :text("x") matches the smallest element that contains x; :text-is("x") requires the exact full text.
  • :has(...) keeps elements that contain a match.
  • :visible drops hidden matches (here the hidden input), like filter(visible=True).

🛤️ XPath

XPath navigates the document as a tree. It can do one thing CSS cannot: move up to parents and ancestors.

📄 tests/test_xpath.py

from playwright.sync_api import Page, expect


def test_xpath_basics(practice: Page):
    # Absolute-anywhere path with an attribute predicate
    practice.locator("//input[@id='username']").fill("xpath_user")
    expect(practice.locator("#username")).to_have_value("xpath_user")

    # Exact text and partial text
    expect(practice.locator("//button[text()='Submit']")).to_be_visible()
    expect(practice.locator("//button[contains(text(), 'Alert')]")).to_have_count(3)

    # Positions are 1-based; (...)[n] picks the nth match overall
    expect(practice.locator("//table/tbody/tr[2]/td[2]")).to_have_text("Rahul")
    expect(practice.locator("(//table//td)[last()]")).to_have_text("Developer")


def test_xpath_axes(practice: Page):
    # following-sibling: the cell after "Rahul" in the same row
    expect(practice.locator("//td[text()='Rahul']/following-sibling::td")).to_have_text("Tester")

    # preceding-sibling: the cell before "Rahul"
    expect(practice.locator("//td[text()='Rahul']/preceding-sibling::td")).to_have_text("2")

    # Going UP: the row (ancestor) that contains "Anita"
    expect(practice.locator("//td[text()='Anita']/ancestor::tr")).to_contain_text("Developer")

    # .. is the parent: the section around the "Iframe" heading
    expect(practice.locator("//h2[text()='Iframe']/..").locator("iframe")).to_have_id("sampleIframe")
XPathMeaning
//tagtag anywhere in the page
[@attr='v']Attribute equals
[text()='x'] / [contains(text(), 'x')]Exact / partial text
[2], [last()]Position (1-based)
/following-sibling::tdSiblings after the element
/preceding-sibling::tdSiblings before the element
/ancestor::trAn ancestor of the element
/..The parent element
  • A path in parentheses with an index, (//table//td)[last()], picks from all matches in the page, while //td[last()] would pick the last cell of each row.
  • Chaining .locator("iframe") after an XPath locator searches inside it, just like with CSS.

⚠️ Watch out: XPath does not pierce shadow DOM, and long absolute paths such as /html/body/div[3]/div/main/... break whenever the layout changes. Keep XPath short and anchored on stable text or attributes.


🔀 Mixing Selectors with Locators

You do not have to choose one style per test. Chain whatever reads best:

📄 tests/test_xpath.py

def test_mixing(practice: Page):
    row = practice.get_by_role("row").filter(has_text="Deepesh")       # role + filter
    expect(row.locator("td").nth(2)).to_have_text("Trainer")           # CSS inside it
    expect(row.locator("xpath=./td[1]")).to_have_text("1")             # XPath relative to the row
    expect(practice.locator("css=#country option")).to_have_count(5)   # explicit css= prefix
  • xpath=./td[1] uses an explicit prefix and a relative path (./), so it searches from the row, not from the page root.
  • css= makes the selector type explicit; it is optional for CSS.

⌨️ Terminal

pytest -q -s tests

🖥️ Output

.......                                                                  [100%]
7 passed, 1 warning in 14.25s

✅ Choosing a Selector: Checklist

  1. Can you use get_by_role with a name? Do it.
  2. Is it a form field with a label or placeholder? Use get_by_label or get_by_placeholder.
  3. Does the element have a stable id or test attribute? #id or get_by_test_id is fine.
  4. Need structure (a cell next to another cell, a parent)? Use a short CSS or XPath anchored on text or attributes.
  5. Avoid: auto-generated classes (.css-1x2y3z), long absolute paths, and indexes that depend on layout.

🏋️ 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: Write a CSS selector and an XPath for the input with id username, and a CSS selector for all checked checkboxes.

Show answer
page.locator("#username")
page.locator("xpath=//input[@id='username']")
page.locator("input[type=checkbox]:checked")

Exercise 2: Using XPath, select the “Role” cell in the row of the web table whose name cell is “Rahul”.

Show answer
page.locator("xpath=//table//tr[td[normalize-space()='Rahul']]/td[3]")

In Playwright, a role-based alternative is often clearer: page.get_by_role("row", name="Rahul").get_by_role("cell").nth(2).

Exercise 3: Rewrite this fragile selector into a more stable one: div.container > div:nth-child(3) > button.btn-primary. Assume the button’s text is “Submit”.

Show answer
page.get_by_role("button", name="Submit", exact=True)

If CSS is required, anchor it to stable attributes or text: page.locator("button:has-text('Submit')"). Avoid positions and layout classes that change with design updates.


🧠 MCQ Quiz: CSS and XPath Selectors in Playwright Python

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 CSS selector targets an element with id login?
  2. What does input[name^="user"] match?
  3. What is the difference between div p and div > p?
  4. Which Playwright pseudo-class filters by text?
  5. In XPath, what does // mean?
  6. Which XPath finds a button whose text contains “Save”?
  7. Which axis selects the following siblings in XPath?
  8. How do you force Playwright to treat a string as XPath?
  9. Do XPath selectors pierce shadow DOM in Playwright?
  10. When are CSS or XPath selectors a reasonable choice?

Want a longer, timed test? Take the Module 4 mock interview (20 MCQs in 20 minutes).


❓ Frequently Asked Questions

🤔 CSS or XPath: which is faster?

The difference is negligible in Playwright tests. Choose for readability and stability; CSS is usually shorter, XPath is needed to move up the tree.

🤔 Why does my CSS :nth-child(1) not match the first row?

:nth-child counts all sibling elements of any type, starting at 1. Check that the parent has no other children before the row, or use Playwright’s .nth(0) / .first on the locator instead.

🤔 Can I reuse my Selenium XPath locators?

Yes, page.locator("//...") accepts them. It is a good migration path; then gradually replace fragile ones with role-based locators.

🤔 Is :has-text case-sensitive?

No. :has-text() and :text() are case-insensitive and ignore extra whitespace; :text-is() needs the exact text.


🏁 Summary

  • page.locator() takes CSS by default and XPath for selectors starting with //; prefixes css= and xpath= make it explicit.
  • CSS: ids, classes, attributes and ^=, $=, *=, combinators (space, >, +), :nth-child, :checked, :disabled.
  • Playwright extras: :has-text, :text, :text-is, :has, :visible.
  • XPath adds axes (following-sibling, preceding-sibling, ancestor, ..); keep selectors short and anchored, and prefer get_by_role where possible.

Next, you will perform every kind of user action: clicks, typing, keyboard keys, hover, drag and drop, dropdowns and more.

🎬 Watch the Playwright tutorial series on YouTube!

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

Playwright Python Locators: get_by_role, get_by_label, Filtering and Strictness

Locators are how Playwright finds elements, and choosing good ones is the single biggest factor in whether your tests are stable or flaky. In this lesson you will learn the built-in get_by_* locators and the order to prefer them in, how to narrow results with filter, nth and chaining, why Playwright refuses ambiguous locators (strictness), and how locators reach into shadow DOM, all on the SQA Tools Automation Practice Page.

📖 What You’ll Learn: what a locator is and why it is lazy, the recommended locator priority, get_by_role with name, exact and state options, get_by_label, get_by_placeholder, get_by_text, get_by_alt_text, get_by_title and get_by_test_id, strictness and the real strict mode violation error, first, last and nth, filter with has_text, has and visible, chaining and combining with and_ and or_, counting and reading many elements, and shadow DOM.


🎯 What Is a Locator?

A locator describes how to find element(s) on the page. Creating one does not search the page; the search happens each time you act on it or assert with it. Two consequences make tests stable:

  • If the page re-renders an element, the locator simply finds the new one; you never hold a “stale” reference.
  • Every action and expect() waits until the locator matches an element in the right state.
username = page.get_by_placeholder("Enter username")   # nothing searched yet
username.fill("qa_learner")                            # found, waited for, filled

🏅 Which Locator Should I Use?

Playwright recommends locators that reflect what users see, because they survive changes to CSS classes and page structure:

PriorityLocatorFinds elements by
1get_by_role(role, name=...)ARIA role and accessible name: buttons, links, checkboxes, headings, rows…
2get_by_label(text)The text of the <label> linked to a form field
3get_by_placeholder(text)An input’s placeholder
4get_by_text(text)Visible text (for non-interactive elements)
5get_by_alt_text(text) / get_by_title(text)An image’s alt text / a title attribute
6get_by_test_id(id)A dedicated test attribute such as data-testid
7locator("css or xpath")CSS or XPath selectors (next lesson)

The rest of this lesson tests each of them on the practice page. All examples live in tests/test_locators.py and share one fixture that opens the page:

📄 tests/conftest.py

import pytest
from playwright.sync_api import Page

URL = "https://sqatools.in/automation-practice-page/"


@pytest.fixture
def practice(page: Page) -> Page:
    page.goto(URL)
    return page

🧭 get_by_role: The First Choice

📄 tests/test_locators.py

import re

from playwright.sync_api import Page, expect


def test_get_by_role(practice: Page):
    # Buttons, matched by their accessible name (the visible text)
    expect(practice.get_by_role("button", name="Submit")).to_be_visible()

    # Headings, optionally by level (h2 = level 2)
    expect(practice.get_by_role("heading", name="Web Table", level=2)).to_be_visible()

    # Radio buttons and checkboxes, by their label
    practice.get_by_role("radio", name="Female").check()
    expect(practice.get_by_role("radio", name="Female")).to_be_checked()

    # State filters: only checkboxes that are currently checked
    practice.get_by_role("checkbox", name="Python").check()
    expect(practice.get_by_role("checkbox", checked=True)).to_have_count(1)

    # Links and table rows
    expect(practice.get_by_role("link", name="Open Google")).to_have_attribute("target", "_blank")
    expect(practice.get_by_role("row", name="2 Rahul Tester")).to_be_visible()
  • The first argument is the role: button, link, textbox, checkbox, radio, combobox (a dropdown), heading, row, cell, img and many more. HTML elements have implicit roles: <button> is a button, <a href> is a link, <input type="checkbox"> is a checkbox.
  • name= matches the accessible name: the button text, the link text, the label of a field. By default the match is case-insensitive and also matches a substring. Pass exact=True for an exact, case-sensitive match, or a compiled regex for patterns.
  • Extra options narrow the match: level= for headings, checked=, disabled=, expanded=, selected= and pressed= for states.
  • A table row’s accessible name is the text of its cells joined with spaces, which is why "2 Rahul Tester" matches the second data row.

💡 Tip: Not sure what role or name an element has? Use Codegen’s Pick locator (Lesson 7), or print page.locator("body").aria_snapshot() to see the page the way get_by_role sees it.


🏷️ Placeholder, Label, Text, Alt Text and Title

📄 tests/test_locators.py

def test_other_get_by_locators(practice: Page):
    # Placeholder text of an input
    practice.get_by_placeholder("Enter username").fill("qa_learner")
    expect(practice.get_by_placeholder("Enter username")).to_have_value("qa_learner")

    # The label next to a checkbox: <input id="python"> <label for="python">Python</label>
    expect(practice.get_by_label("Python", exact=True)).not_to_be_checked()

    # Visible text of a non-interactive element
    expect(practice.get_by_text("This is the bottom of the page for scrolling practice.")).to_be_attached()

    # An image's alt text, and an element's title attribute
    expect(practice.get_by_alt_text("Sample Image")).to_be_visible()
    expect(practice.get_by_title("Hover text")).to_have_text("Hover Over Me")
  • get_by_label finds the form control that a <label> points to (or wraps). It is the best choice for forms with proper labels.
  • get_by_text is for content such as paragraphs and messages. For buttons and links, prefer get_by_role(..., name=...), which also checks the element type.
  • exact=True matters here: without it, get_by_label("Python") would also match any label that merely contains “Python”.
  • to_be_attached() checks that the element exists in the page; to_be_visible() additionally needs it to be visible.

🧪 get_by_test_id and a Custom Test Attribute

Many teams add attributes purely for testing, such as data-testid="login-button". get_by_test_id("login-button") finds them. By default Playwright looks at data-testid; if your app uses another name, change it once, for example in a session fixture in conftest.py:

import pytest


@pytest.fixture(scope="session", autouse=True)
def configure_test_id(playwright):
    playwright.selectors.set_test_id_attribute("data-test")

Sauce Demo uses data-test, so after this setting page.get_by_test_id("login-button") finds its login button. Test IDs are very stable, but users do not see them, so role-based locators are still preferred where they work.

📄 tests/test_test_id.py

import pytest
from playwright.sync_api import Page, expect


@pytest.fixture(scope="session", autouse=True)
def configure_test_id(playwright):
    playwright.selectors.set_test_id_attribute("data-test")


def test_get_by_test_id(page: Page):
    page.goto("https://www.saucedemo.com/")
    page.get_by_test_id("username").fill("standard_user")
    page.get_by_test_id("password").fill("secret_sauce")
    page.get_by_test_id("login-button").click()
    expect(page.get_by_test_id("title")).to_have_text("Products")

⚠️ Strictness: One Locator, One Element

When you act on a locator (click, fill, check…), it must match exactly one element. If it matches several, Playwright refuses to guess and raises a *strict mode violation*. The practice page has a perfect example: its “Click to Replace Me” button adds a second button with the same id, which is invalid HTML but common in real apps:

📄 tests/test_strictness.py

import pytest
from playwright.sync_api import Error, Page, expect


def test_strict_mode_violation(practice: Page):
    practice.get_by_role("button", name="Click to Replace Me").click()

    with pytest.raises(Error) as info:
        practice.locator("#staleBtn").click(timeout=2000)
    print("\n" + str(info.value).splitlines()[0])

    # Fix 1: a more specific locator
    expect(practice.get_by_role("button", name="New Button (Old is Stale)")).to_be_visible()
    # Fix 2: say which match you want
    expect(practice.locator("#staleBtn").last).to_have_text("New Button (Old is Stale)")
    # Counting is allowed: assertions on many elements are not strict
    expect(practice.locator("#staleBtn")).to_have_count(2)

🖥️ Output

Locator.click: Error: strict mode violation: locator("#staleBtn") resolved to 2 elements:

The full error message lists both elements and even suggests better locators:

🖥️ Output

1) <button id="staleBtn" onclick="replaceElement()">Click to Replace Me</button> aka get_by_role("button", name="Click to Replace Me")
2) <button id="staleBtn">New Button (Old is Stale)</button> aka get_by_role("button", name="New Button (Old is Stale)")

Strictness is a feature: without it, a test could click the wrong one of two “Delete” buttons and still pass. Fix violations by making the locator more specific, or by choosing explicitly with .first, .last or .nth(index).


🔬 Narrowing Down: nth, filter and Chaining

📄 tests/test_locators.py

def test_narrowing(practice: Page):
    rows = practice.get_by_role("row")                     # header + 3 data rows

    # Position: first, last, nth (0-based)
    expect(rows.first).to_contain_text("ID Name Role")
    expect(rows.nth(1)).to_contain_text("Deepesh")
    expect(rows.last).to_contain_text("Anita")

    # filter(has_text=...): keep elements that contain the text
    tester_row = rows.filter(has_text="Tester")
    expect(tester_row).to_have_count(1)

    # Chaining: search inside another locator
    expect(tester_row.get_by_role("cell").first).to_have_text("2")

    # filter(has=...): keep elements that contain a matching child
    trainer = practice.get_by_role("row").filter(has=practice.get_by_role("cell", name="Trainer"))
    expect(trainer).to_contain_text("Deepesh")

    # Data rows contain "cell"s (the header row has "columnheader"s); has_not_text excludes
    data_rows = rows.filter(has=practice.get_by_role("cell"))
    expect(data_rows).to_have_count(3)
    expect(data_rows.filter(has_not_text="Anita")).to_have_count(2)

    # has_text also accepts a regular expression
    expect(rows.filter(has_text=re.compile(r"Rahul|Anita"))).to_have_count(2)
  • .first, .last and .nth(i) pick by position. Use them deliberately: position-based locators break when the order changes.
  • filter(has_text=...) keeps matches containing the text (or matching a regex); has_not_text= does the opposite.
  • filter(has=locator) keeps elements that contain an element matching the inner locator; has_not= excludes them.
  • Calling a locator method on another locator (tester_row.get_by_role("cell")) searches inside it. This is called chaining and is the cleanest way to scope a search to one card, row or dialog.
  • filter(has=practice.get_by_role("cell")) keeps only data rows, because the header row’s cells have the role columnheader, not cell. This is more robust than matching text.
  • re.compile(r"Rahul|Anita") keeps rows whose text contains either name. Regex filters match anywhere in the element’s text, which includes surrounding whitespace, so avoid anchors like ^ unless you account for it.

Visible elements only, and combining locators

📄 tests/test_locators.py

def test_visible_and_combinations(practice: Page):
    # The hidden input exists but is not visible; filter(visible=True) skips it
    text_inputs = practice.locator("input[type='text']")
    print(f"\ntext inputs: {text_inputs.count()}, visible: {text_inputs.filter(visible=True).count()}")
    expect(practice.locator("#hiddenField")).to_be_hidden()

    # and_: both conditions must match the same element
    submit = practice.get_by_role("button").and_(practice.locator("#submitButton"))
    expect(submit).to_have_text("Submit")

    # or_: either locator (handy when a page shows one of two variants)
    alert_or_confirm = practice.get_by_role("button", name="Simple Alert").or_(
        practice.get_by_role("button", name="Confirm Alert"))
    expect(alert_or_confirm).to_have_count(2)
  • filter(visible=True) keeps only visible matches.
  • and_() requires both locators to match the same element; or_() matches elements of either.

📋 Reading Many Elements

📄 tests/test_locators.py

def test_reading_lists(practice: Page):
    options = practice.locator("#country option")
    print("\ncountries:", options.all_inner_texts())

    names = [row.get_by_role("cell").nth(1).inner_text()
             for row in practice.locator("table tbody tr").all()]
    print("names:", names)
    assert names == ["Deepesh", "Rahul", "Anita"]
  • count() returns how many elements match right now.
  • all_inner_texts() returns a list of the visible texts.
  • all() returns a list of locators, one per match, to loop over. Like count(), it does not wait; make sure the list has loaded (for example with an expect) before calling it.

🌘 Shadow DOM

Web components hide their inner elements in a shadow root. Playwright’s role, text, label and CSS locators pierce open shadow roots automatically, even nested ones. The practice page has a button two shadow roots deep:

📄 tests/test_locators.py

def test_shadow_dom(practice: Page):
    practice.get_by_placeholder("Nested Shadow Input").fill("inside the shadow DOM")
    expect(practice.get_by_placeholder("Nested Shadow Input")).to_have_value("inside the shadow DOM")
    expect(practice.locator("#shadowBtn")).to_have_text("Shadow Button")
    expect(practice.get_by_text("Nested Shadow DOM Text")).to_be_visible()

No special syntax is needed. (XPath is the exception: it does not pierce shadow roots, one more reason to prefer the other locators.)


▶️ Run All Examples

⌨️ Terminal

pytest -q -s tests

🖥️ Output

...
text inputs: 7, visible: 6
.
countries: ['–Select Country–', 'India', 'USA', 'UK', 'Australia']
names: ['Deepesh', 'Rahul', 'Anita']
..
Locator.click: Error: strict mode violation: locator("#staleBtn") resolved to 2 elements:
..
8 passed, 1 warning in 16.91s

Seven text inputs exist but only six are visible: the seventh is the hidden field. The warning is the pytest-playwright notice you can silence with filterwarnings (Lesson 29).


🏋️ 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: On the SQA Tools automation practice page, write locators for: the username field by its placeholder, the “Submit” button by role, and the Python checkbox by its label.

Show answer
page.get_by_placeholder("Enter username")
page.get_by_role("button", name="Submit", exact=True)
page.get_by_label("Python")

exact=True matters for buttons whose names are substrings of others.

Exercise 2: Write a locator for the “Add to cart” button inside the SQA Shop product card that contains “Wireless Earbuds”, then click it.

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

Exercise 3: Print the names of all products on the first SQA Shop results page and the number of cards.

Show answer
cards = page.get_by_test_id("product-card")
print(cards.count())
print(page.get_by_test_id("product-name").all_inner_texts())

Use expect(cards.first).to_be_visible() first so the list has rendered.


🧠 MCQ Quiz: Playwright Python Locators: get_by_role and More

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. When does Playwright search for the element of a locator?
  2. Which locator is at the top of Playwright’s recommended priority?
  3. What does exact=True change in get_by_text("Login", exact=True)?
  4. Which locator uses the data-testid attribute by default?
  5. What happens if a locator matches three elements and you call fill()?
  6. How do you select the second matching element?
  7. What does filter(has=page.get_by_role("button", name="Buy")) keep?
  8. What does locator_a.or_(locator_b) do?
  9. Does get_by_role pierce open shadow DOM?
  10. Which method returns the texts of all matched elements?

Want a longer, timed test? Take the Module 4 mock interview (20 MCQs in 20 minutes).


❓ Frequently Asked Questions

🤔 Why does get_by_role(“button”, name=”Submit”) also match “Submit order”?

Name matching is a case-insensitive substring match by default. Use exact=True or a regex such as re.compile(r"^Submit$") when other buttons contain the same word.

🤔 Is get_by_text fine for buttons?

It works, but get_by_role("button", name=...) is better: it also checks that the element really is a button and ignores matching text elsewhere.

🤔 Do locators wait for elements?

Actions and expect() wait (up to their timeouts). Methods that return information immediately, such as count(), all() and is_visible(), do not.

🤔 What does “resolved to 2 elements” mean?

The locator matched two elements while an action needed exactly one. Make it more specific, scope it by chaining, or use .first, .last or .nth() on purpose.


🏁 Summary

  • Prefer user-facing locators: get_by_role first, then label, placeholder, text, alt text, title and test id; CSS/XPath last.
  • Locators are lazy and re-evaluated on every use; actions and expect wait for them.
  • Strictness rejects ambiguous locators; fix with specificity, chaining, filter, or explicit first/last/nth.
  • filter(has_text=, has=, visible=), and_, or_, all() and all_inner_texts() cover almost every real page, and locators pierce open shadow DOM.

Next, you will learn CSS and XPath selectors for the cases where the get_by locators are not enough.

🎬 Watch the Playwright tutorial series on YouTube!

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