Debugging Playwright Python Tests: Inspector, PWDEBUG, page.pause and breakpoint

A failing test is a question: what did the page really look like when the step failed? Playwright Python gives you several ways to answer it, from reading the error message properly to stepping through a test in a live browser. In this lesson you will learn a debugging routine that works: read Playwright’s call log, reproduce one test headed and slowed down, open the Playwright Inspector with PWDEBUG, stop at a line with page.pause or breakpoint, log every API call with DEBUG=pw:api, capture the page’s console errors, and debug in VS Code.

Advertisement

📖 What You’ll Learn: a step-by-step debugging routine, reading the call log and aria snapshot in errors, strict mode violations, -x, –lf, -k and –tb to narrow a failure, –headed and –slowmo, PWDEBUG=1 and the Playwright Inspector, page.pause(), breakpoint() and pytest –pdb, DEBUG=pw:api logging, capturing console messages and page errors, locator.highlight(), screenshots mid-test, and debugging in VS Code with launch.json.


🧭 A Debugging Routine

When a test fails, work through these steps in order. Most failures are solved by step 2.

  1. Run only the failing test (-k, --lf, node id).
  2. Read the whole error: the call log and the aria snapshot usually say exactly what happened.
  3. Watch it: --headed --slowmo 500.
  4. Step through it: PWDEBUG=1 or page.pause().
  5. Look after the fact: the trace (next lesson), screenshots and videos.

🎯 Step 1: Narrow the Failure

📄 pytest.ini

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

📄 tests/test_shop.py

from playwright.sync_api import Page, expect

SHOP = "/dummy-ecommerce-website/"


def test_home_has_products(page: Page):
    page.goto(SHOP)
    expect(page.get_by_test_id("product-card").first).to_be_visible()


def test_add_first_product(page: Page):
    page.goto(SHOP)
    page.get_by_role("button", name="Add to cart").click(timeout=3_000)   # bug: which product?


def test_login_greeting(page: Page):
    page.goto(SHOP + "#/login")
    page.get_by_test_id("login-username").fill("testuser")
    page.get_by_test_id("login-password").fill("Test@123")
    page.get_by_test_id("login-button").click()
    expect(page.get_by_test_id("account-button")).to_have_text("Hello, Test", timeout=3_000)   # bug: wrong text

⌨️ Terminal

pytest -q --tb=no

🖥️ Output

.FF                                                                      [100%]
=========================== short test summary info ===========================
FAILED tests/test_shop.py::test_add_first_product[chromium] - playwright._imp...
FAILED tests/test_shop.py::test_login_greeting[chromium] - AssertionError: Lo...
2 failed, 1 passed in 8.37s

Useful selection options while debugging:

Option Effect
-x Stop at the first failure
--lf Run only the tests that failed last time
-k login Run tests whose name matches
tests/test_shop.py::test_login_greeting Run exactly one test
--tb=short / --tb=line / --tb=no Shorter or no tracebacks

⌨️ Terminal

pytest --lf -q --tb=no

🖥️ Output

FF                                                                       [100%]
=========================== short test summary info ===========================
FAILED tests/test_shop.py::test_add_first_product[chromium] - playwright._imp...
FAILED tests/test_shop.py::test_login_greeting[chromium] - AssertionError: Lo...
2 failed in 6.61s

📜 Step 2: Read the Call Log

Playwright errors contain much more than “timeout”. Run one failing test with its full output:

⌨️ Terminal

pytest tests/test_shop.py::test_add_first_product -q

🖥️ Output

>           return await func()
                   ^^^^^^^^^^^^
E           playwright._impl._errors.Error: Locator.click: Error: strict mode violation: get_by_role("button", name="Add to cart") resolved to 12 elements:
E               1) <button type="button" class="sp-btn sm" data-add="EL-039" data-testid="add-to-cart-EL-039">Add to cart</button> aka get_by_test_id("add-to-cart-EL-039")
E               2) <button type="button" class="sp-btn sm" data-add="EL-021" data-testid="add-to-cart-EL-021">Add to cart</button> aka get_by_test_id("add-to-cart-EL-021")
E               3) <button type="button" class="sp-btn sm" data-add="EL-007" data-testid="add-to-cart-EL-007">Add to cart</button> aka get_by_test_id("add-to-cart-EL-007")
E               4) <button type="button" class="sp-btn sm" data-add="EL-020" data-testid="add-to-cart-EL-020">Add to cart</button> aka get_by_test_id("add-to-cart-EL-020")
E               5) <button type="button" class="sp-btn sm" data-add="DG-010" data-testid="add-to-cart-DG-010">Add to cart</button> aka get_by_test_id("add-to-cart-DG-010")
E               6) <button type="button" class="sp-btn sm" data-add="CL-023" data-testid="add-to-cart-CL-023">Add to cart</button> aka get_by_test_id("add-to-cart-CL-023")
E               7) <button type="button" class="sp-btn sm" data-add="CL-024" data-testid="add-to-cart-CL-024">Add to cart</button> aka get_by_test_id("add-to-cart-CL-024")
E               8) <button type="button" class="sp-btn sm" data-add="EL-012" data-testid="add-to-cart-EL-012">Add to cart</button> aka get_by_test_id("add-to-cart-EL-012")
E               9) <button type="button" class="sp-btn sm" data-add="CL-035" data-testid="add-to-cart-CL-035">Add to cart</button> aka get_by_test_id("add-to-cart-CL-035")
E               10) <button type="button" class="sp-btn sm" data-add="CL-001" data-testid="add-to-cart-CL-001">Add to cart</button> aka get_by_test_id("add-to-cart-CL-001")
E               ...
E           
E           Call log:
E             - waiting for get_by_role("button", name="Add to cart")

..\..\.venv\Lib\site-packages\playwright\_impl\utils\zones.py:58: Error
=========================== short test summary info ===========================
FAILED tests/test_shop.py::test_add_first_product[chromium] - playwright._imp...
1 failed in 2.05s

The message says it all: strict mode violation. The locator matched every “Add to cart” button on the page, and Playwright refuses to guess which one you meant. It lists the first matches with a suggested unique locator for each. Fix the test by saying which product you mean, for example page.get_by_test_id("product-card").filter(has_text="Wireless Earbuds").get_by_role("button", name="Add to cart"), or .first if any product will do.

⌨️ Terminal

pytest tests/test_shop.py::test_login_greeting -q

🖥️ Output

        page.get_by_test_id("login-button").click()
>       expect(page.get_by_test_id("account-button")).to_have_text("Hello, Test", timeout=3_000)   # bug: wrong text
        ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
E       AssertionError: Locator expected to have text 'Hello, Test'
E       Actual value: Hi, Test 
E       Call log:
E         - Expect "to_have_text" get_by_test_id("account-button") with timeout 3000ms
E         - waiting for get_by_test_id("account-button")
E           10 × locator resolved to <button type="button" class="sp-tool" id="account-btn" aria-haspopup="true" aria-expanded="false" data-testid="account-button">…</button>
E              - unexpected value "Hi, Test"
E       
E       Aria snapshot:
E       - button "Hi, Test"

tests\test_shop.py:21: AssertionError
=========================== short test summary info ===========================
FAILED tests/test_shop.py::test_login_greeting[chromium] - AssertionError: Lo...
1 failed in 4.85s

For a failed assertion the call log shows how often Playwright re-checked (9 × locator resolved to ...), the actual value (“Hi, Test”) and an aria snapshot of the element. Here the test, not the app, is wrong.

💡 Tip: Read errors from the bottom up: the last lines of the call log describe the final state of the page. Most “flaky” failures are explained there: the element existed but was hidden, disabled, covered or had different text.


Advertisement

👀 Step 3: Watch the Test Run

⌨️ Terminal

pytest tests/test_shop.py::test_login_greeting --headed --slowmo 500

--headed opens a real browser window and --slowmo 500 waits half a second before every Playwright action, so you can follow along. Add --browser firefox to watch another engine.


🕵️ Step 4a: PWDEBUG and the Playwright Inspector

Setting the environment variable PWDEBUG=1 runs tests headed, sets timeouts to zero (no waiting out a 30 s timeout while you think) and opens the Playwright Inspector, which pauses before the first action:

⌨️ Terminal

$env:PWDEBUG = "1"; pytest tests/test_shop.py::test_add_first_product    # PowerShell
PWDEBUG=1 pytest tests/test_shop.py::test_add_first_product              # macOS / Linux

In the Inspector you can:

  • Step over each Playwright call, or resume to the next pause.
  • See which element each locator matches, highlighted in the browser.
  • Use Pick locator to click an element and get the recommended locator for it.
  • Edit a locator in the Inspector’s field and see the matches live.

Remove the variable afterwards (Remove-Item Env:PWDEBUG in PowerShell, unset PWDEBUG in bash), or it will slow every run.


⏸️ Step 4b: page.pause() at One Line

To stop at one specific point, add page.pause() where you want to look around. Run the test headed (--headed); the Inspector opens at that line with the browser in exactly that state:

def test_add_first_product(page: Page):
    page.goto(SHOP)
    page.pause()                       # Inspector opens here; try locators, then press Resume
    page.get_by_role("button", name="Add to cart").first.click()

page.pause() needs a headed browser, so run the test with --headed (or PWDEBUG=1), and delete the line before committing.


🐞 Step 4c: Python Breakpoints and –pdb

Playwright pauses the browser; Python’s debugger pauses your code, so you can inspect variables and call Playwright interactively:

def test_login_greeting(page: Page):
    ...
    breakpoint()                       # drops into pdb: try page.url, page.get_by_test_id("account-button").inner_text()

Or let pytest open the debugger automatically when a test fails:

⌨️ Terminal

pytest tests/test_shop.py::test_login_greeting --pdb --headed

At the (Pdb) prompt the browser is still open in the failed state. Useful commands: p page.url, p page.get_by_test_id("account-button").inner_text(), l (list code), c (continue), q (quit). Use --pdb together with -s if your test prints output.


Advertisement

📡 Step 5: Log Every Playwright Call

The DEBUG=pw:api environment variable makes Playwright log each API call with timings to stderr. It is invaluable in CI, where you cannot watch the browser:

⌨️ Terminal

$env:DEBUG = "pw:api"; pytest tests/test_shop.py::test_home_has_products -q -s

🖥️ Output

pw:api => BrowserType.launch started
pw:api <= BrowserType.launch succeeded
pw:api => Browser.new_context started
pw:api <= Browser.new_context succeeded
pw:api => BrowserContext.new_page started
pw:api <= BrowserContext.new_page succeeded
pw:api => Page.goto started
pw:api <= Page.goto succeeded
pw:api => LocatorAssertions.to_be_visible started
pw:api <= LocatorAssertions.to_be_visible succeeded
.pw:api => Tracing.stop started
pw:api <= Tracing.stop succeeded
pw:api => BrowserContext.close started
pw:api <= BrowserContext.close succeeded

Each => line is a call starting and each <= line the call finishing, so you can see exactly which call was running when a test hung or failed. (The command filters the output to start/finish lines; unfiltered, pw:api also logs every frame navigation, including the page’s ad iframes.)


🖥️ Capture the Page’s Own Errors

Many UI failures start with a JavaScript error in the application. Collect console messages and uncaught page errors in a fixture, and print them when a test fails:

📄 tests/conftest.py

import pytest
from playwright.sync_api import Page


@pytest.fixture(autouse=True)
def browser_log(page: Page):
    messages = []
    page.on("console", lambda msg: messages.append(f"console.{msg.type}: {msg.text}") if msg.type in ("error", "warning") else None)
    page.on("pageerror", lambda err: messages.append(f"pageerror: {err}"))
    yield messages
    if messages:
        print("\n--- browser log ---\n" + "\n".join(messages[:10]))

📄 tests/test_page_errors.py

from playwright.sync_api import Page


def test_page_with_js_error(page: Page, browser_log):
    page.set_content("<button onclick=\"undefinedFunction()\">Buy</button><script>console.error('price service unavailable')</script>")
    page.get_by_role("button", name="Buy").click()
    page.wait_for_timeout(200)          # give the click handler a moment; only for this demonstration
    assert any("undefinedFunction" in m for m in browser_log)

⌨️ Terminal

pytest tests/test_page_errors.py -q -s

🖥️ Output

.
--- browser log ---
console.error: price service unavailable
pageerror: undefinedFunction is not defined

1 passed in 0.73s

pageerror catches uncaught exceptions (here, calling an undefined function) and console catches console.error() messages the app logs. Printing them on failure often explains the failure before you open a trace.


🔦 Quick Tricks Inside a Test

Trick Use
locator.highlight() Outline the matched element in headed runs
print(locator.count()) How many elements match right now
print(locator.all_inner_texts()) What the matched elements contain
page.screenshot(path="debug.png", full_page=True) A picture of this exact moment
print(page.get_by_test_id("filters").aria_snapshot()) The accessible structure of a region as text

📄 tests/test_tricks.py

from playwright.sync_api import Page


def test_inspect_buttons(page: Page):
    page.goto("/dummy-ecommerce-website/")
    buttons = page.get_by_role("button", name="filters")
    print("\nmatches:", buttons.count(), buttons.all_inner_texts())
    page.screenshot(path="debug-home.png")

⌨️ Terminal

pytest tests/test_tricks.py -q -s

🖥️ Output

matches: 1 ['Clear all filters']
.
1 passed in 1.89s

The output shows a trap that no error message would reveal. The test meant the “Filters” button, but at desktop width that button is hidden, and role names match substrings, case-insensitively by default, so name="filters" matched exactly one visible button: “Clear all filters”. A click() would have succeeded on the wrong button. count() and all_inner_texts() expose this in seconds; exact=True (name="Filters", exact=True) prevents it.


🧑‍💻 Debugging in VS Code

With the Python extension, VS Code’s Testing panel runs and debugs pytest tests directly: right-click a test and choose Debug Test, and red-dot breakpoints in your test or page objects work. To debug headed, add the options to a launch configuration:

{
  "version": "0.2.0",
  "configurations": [
    {
      "name": "Debug current Playwright test (headed)",
      "type": "debugpy",
      "request": "launch",
      "module": "pytest",
      "args": ["${file}", "--headed", "--slowmo", "300", "-s"],
      "console": "integratedTerminal",
      "justMyCode": false
    }
  ]
}

Save it as .vscode/launch.json, open a test file and press F5.


Advertisement

🏋️ Practice Exercises

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

Exercise 1: Write a test that opens the “Filters” panel on a phone-sized viewport, using a locator that cannot match “Clear all filters”, and checks that the panel becomes visible.

Show answer
def test_open_filters(page: Page):
    page.set_viewport_size({"width": 400, "height": 800})
    page.goto(SHOP)
    page.get_by_role("button", name="Filters", exact=True).click()
    expect(page.get_by_test_id("filters")).to_be_visible()

exact=True makes the role name match the whole name, so “Clear all filters” no longer matches. The button only exists on narrow screens (Lesson 50), and a fresh load at 400 px starts with the panel closed, so the click really opens it.

Exercise 2: A test passes locally and fails in CI with a timeout on click(). Which two debugging tools from this lesson help most when you cannot watch the CI browser?

Show answer

DEBUG=pw:api (logs every Playwright call with timings, showing where it waited) and the call log in the error message (shows the element’s state on every retry: hidden, disabled, covered). Add traces and screenshots on failure (Lesson 60, next lesson) for a full picture.

Exercise 3: Write the command that runs only the tests that failed in the previous run, stops at the first failure, and opens pdb there with the browser visible.

Show answer
pytest --lf -x --pdb --headed

Exercise 4: Your app logs console.error("Payment SDK failed to load") but the test only fails later with a timeout. Write an autouse fixture that fails the test early (in teardown) if any console error was logged.

Show answer
@pytest.fixture(autouse=True)
def no_console_errors(page):
    errors = []
    page.on("console", lambda m: errors.append(m.text) if m.type == "error" else None)
    yield
    assert not errors, f"console errors: {errors}"

Use an allow-list for known, harmless third-party errors so the check stays useful.


🧠 MCQ Quiz: Debugging: Inspector, PWDEBUG and page.pause

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 should you do first when a Playwright test fails?
  2. What does a “strict mode violation” mean?
  3. What does --slowmo 500 do?
  4. What does PWDEBUG=1 enable?
  5. Where does page.pause() stop?
  6. What does pytest --pdb do?
  7. What does DEBUG=pw:api log?
  8. Which page event reports uncaught JavaScript exceptions?
  9. How do you see how many elements a locator matches at the moment?
  10. Which option re-runs only the tests that failed in the previous run?

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


Advertisement

❓ Frequently Asked Questions

🤔 Why does my test pass in headed mode but fail headless?

Headless browsers use a different default viewport (1280×720) and no visible window focus, and timing is slightly different. Set the viewport explicitly, avoid relying on hover or focus side effects, and use expect instead of fixed waits. Compare traces from both runs.

🤔 Can I attach the Playwright Inspector to a CI run?

No, CI has no screen. Use traces (--tracing retain-on-failure), screenshots and videos, plus DEBUG=pw:api logs, and debug locally with the trace viewer.

🤔 How do I find a good locator quickly?

Use Pick locator in the Inspector (PWDEBUG=1 or page.pause()), or playwright codegen <url> (Lesson 7). Both recommend role and test-id based locators.

🤔 Does page.pause() work with pytest-xdist?

Not usefully: parallel workers have no interactive console. Run the test alone, without -n, when you need to pause it.

🤔 Why are my print() calls not shown?

pytest captures output by default and shows it only for failing tests. Run with -s (or --capture=no) to see prints live, or use logging with log_cli (Lesson 60).


🏁 Summary

  • Narrow the failure (-k, --lf, node ids) and read the full error: call log, actual value, aria snapshot.
  • Watch with --headed --slowmo, step through with PWDEBUG=1 or page.pause(), inspect code with breakpoint() or --pdb.
  • Log Playwright calls with DEBUG=pw:api, and collect console and pageerror events from the app.
  • Use count(), all_inner_texts(), highlight(), screenshots and aria snapshots for quick checks.
  • Debug in VS Code’s Testing panel or with a launch.json that runs pytest headed.

🎬 Watch the Playwright tutorial series on YouTube!

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