🛠️ Live Interactive Debugging: The Playwright Inspector
Debugging broken selectors, timing mismatches, and unexpected modal overlays in automated test scripts often leads developers to insert brittle print statements or arbitrary sleeps. Playwright Inspector is a dedicated standalone GUI tool built directly into the Playwright engine for live, step-through debugging. Activated via the environment variable PWDEBUG=1 or programmatically placed page.pause() statements, the Inspector halts test execution at exact script coordinates, opens the browser in headed mode with devtools attached, highlights target elements with color-coded overlays, and provides an Explore & Pick Locator tool that automatically suggests resilient, accessible Playwright locators (such as get_by_role() and get_by_test_id()).
PLAYWRIGHT INSPECTOR DEBUGGING PIPELINE:
[ Terminal / IDE Invocation: PWDEBUG=1 pytest ] OR [ Script Encounter: page.pause() ]
│
▼
┌─────────────────────────────────────────────────────────────────────────────┐
│ 1. RUNTIME STATE MUTATIONS │
│ * Headless mode automatically overridden to Headed │
│ * Default timeouts set to 0 (Infinity - never times out while inspecting)│
│ * Launches synchronized Playwright Inspector GUI alongside browser │
└─────────────────────────────────────────────────────────────────────────────┘
│
▼
┌─────────────────────────────────────────────────────────────────────────────────┐
│ 2. PLAYWRIGHT INSPECTOR GUI CONTROLS │
│ ├── Resume (F8) ──► Resumes test execution until next page.pause() │
│ ├── Step Over (F10) ──► Advances execution by exactly ONE line of code │
│ ├── Record (Codegen) ──► Captures live user clicks & typing into Python │
│ ├── Pick Locator ──► Hover over DOM to generate accessible selector │
│ └── Locator Query Box ──► Test CSS, XPath, or Role locators in live DOM │
└─────────────────────────────────────────────────────────────────────────────────┘
│
▼
┌───────────────────────────────────────────────────────────────────────────────┐
│ 3. LIVE DOM SYNCHRONIZATION: BROWSER DEVTOOLS CONSOLE │
│ * playwrite.$("#item") ──► Evaluates and logs DOM element reference │
│ * playwrite.$$("button") ──► Returns collection array of matching nodes │
│ * playwrite.inspect() ──► Highlights element directly in DevTools tree │
└───────────────────────────────────────────────────────────────────────────────┘
page.pause() inside any Playwright Python script. Execution freezes at that exact line, opening the Inspector GUI so you can step through subsequent actions.
from playwright.sync_api import sync_playwright, expect
with sync_playwright() as p:
# Launch browser - page.pause() automatically forces headed view
browser = p.chromium.launch(headless=False)
context = browser.new_context()
page = context.new_page()
page.goto("https://demo.playwright.dev/todomvc/")
expect(page).to_have_title("React • TodoMVC")
new_todo = page.get_by_placeholder("What needs to be done?")
new_todo.fill("Validate Enterprise Payment Gateway")
new_todo.press("Enter")
# 🛑 BREAKPOINT: Halts execution here, opens Playwright Inspector window!
print("Execution paused at breakpoint. Inspecting live browser state...")
page.pause()
# The actions below execute step-by-step as you click 'Step Over' (F10) in Inspector:
todo_item = page.locator(".todo-list li").first
todo_item.locator(".toggle").check()
expect(todo_item).to_have_class("completed")
context.close()
browser.close()
PWDEBUG=1 environment variable.
# 1. Run a specific test with Playwright Inspector attached from line 1 (Linux/macOS)
PWDEBUG=1 pytest tests/test_checkout.py -k "test_order_submission"
# 2. Windows PowerShell syntax for launching with PWDEBUG
$env:PWDEBUG="1"; pytest tests/test_checkout.py
# 3. Windows Command Prompt (CMD) syntax
set PWDEBUG=1 && pytest tests/test_checkout.py
# 4. Debug standalone Python script with PWDEBUG enabled
PWDEBUG=1 python scripts/verify_portal_login.py
# 5. Launch Inspector with console DevTools opened automatically
PWDEBUG=console pytest tests/test_orders.py
from playwright.sync_api import sync_playwright, expect
with sync_playwright() as p:
browser = p.chromium.launch(headless=False)
page = browser.new_page()
page.set_content("""
Enterprise Invoicing Console
""")
# Pause execution to use "Pick Locator" in Inspector GUI
page.pause()
# The Inspector's "Pick Locator" generates clean role-based selectors:
# ❌ Brittle CSS: page.locator("#btn-submit-8841") or page.locator(".btn.primary-action")
# ✅ Resilient Accessible Role: page.get_by_role("button", name="Submit Invoice Ledger")
client_field = page.get_by_placeholder("Enter corporate client")
submit_button = page.get_by_role("button", name="Submit Invoice Ledger")
client_field.fill("Nikita Infotech Systems")
submit_button.click()
expect(page.locator("#output")).to_have_text("LEDGER_GENERATED_SUCCESSFULLY")
browser.close()
playwright object into the browser's Developer Tools Console, enabling live interactive querying of selector engines.
// RUN THESE COMMANDS DIRECTLY IN BROWSER DEVTOOLS CONSOLE DURING page.pause():
// 1. Query a single element using Playwright's role selector engine:
playwright.$("role=button[name='Generate Ledger']")
// ──► Logs:
playwright codegen to record manual browser clicks, keystrokes, and assertions in real time, emitting idiomatic, clean Python Playwright code instantly.
# 1. Open Codegen against target application URL with Python output
playwright codegen https://demo.playwright.dev/todomvc/
# 2. Record with mobile device viewport & user agent emulation
playwright codegen --device="iPhone 14 Pro" https://demo.playwright.dev/todomvc/
# 3. Record session preserving pre-authenticated storage state JSON
playwright codegen --load-storage=auth.json https://nikita-infotech.com/admin
# 4. Save recorded session directly into a ready-to-run Python file
playwright codegen -o tests/test_recorded_checkout.py https://demo.playwright.dev/todomvc/
# 5. Specify target browser engine for recording session
playwright codegen -b firefox https://example.com
# content of conftest.py
import pytest
from playwright.sync_api import Page
def pytest_addoption(parser):
parser.addoption(
"--pause-on-failure",
action="store_true",
default=False,
help="Opens Playwright Inspector when an assertion or action failure occurs"
)
@pytest.hookimpl(tryfirst=True, hookwrapper=True)
def pytest_runtest_makereport(item, call):
outcome = yield
report = outcome.get_result()
# Check if test failed during the execution phase and pause flag is active
if report.when == "call" and report.failed:
if item.config.getoption("--pause-on-failure"):
page: Page = item.funcargs.get("page")
if page:
print(f"\n[Inspector Hook] Test '{item.name}' failed! Freezing browser for interactive inspection...")
page.pause()
# Execution CLI:
# pytest tests/test_billing.py --pause-on-failure
page.route(), inspecting headers and status codes in real time inside the browser while stepping through your test.
import json
from playwright.sync_api import sync_playwright, expect
with sync_playwright() as p:
browser = p.chromium.launch(headless=False)
page = browser.new_page()
# Step 1: Set up network mock route
def handle_balance_api(route):
print(f"[Route Intercepted] Mocking {route.request.url} with custom payload")
route.fulfill(
status=200,
content_type="application/json",
body=json.dumps({"account": "ACC-9921", "balance_inr": 2500000.0, "status": "VERIFIED"})
)
page.route("**/api/v1/account-balance", handle_balance_api)
# 🛑 BREAKPOINT 1: Verify route is registered before navigating
page.pause()
# Step 2: Trigger UI view that requests the mocked endpoint
page.set_content("""
Wallet Dashboard
₹ 0.00
Pending
""")
page.locator("#refresh-btn").click()
# 🛑 BREAKPOINT 2: Verify UI correctly rendered the mocked payload
page.pause()
expect(page.locator("#bal")).to_have_text("₹ 2,500,000")
expect(page.locator("#status")).to_have_text("VERIFIED")
browser.close()
from playwright.sync_api import sync_playwright, expect
with sync_playwright() as p:
browser = p.chromium.launch(headless=False)
page = browser.new_page()
# Simulate button that is rendered in DOM but disabled by background API
page.set_content("""
Software License Agreement
I agree to terms
""")
# Attempt to click disabled button
activate_button = page.locator("#activate-license")
# In headless CI, this raises: TimeoutError: locator.click: Timeout 30000ms exceeded.
# In Inspector mode (PWDEBUG=1), you can see the action log waiting:
# waiting for locator("#activate-license")
# locator resolved to
PLAYWRIGHT INSPECTOR & DEBUGGING REFERENCE MATRIX:
┌──────────────────────────────┬──────────────────────────────┬─────────────────────────────────────────────────────────┐
│ Control / Environment / Tool │ Syntax / Command │ Description / Primary Use Case │
├──────────────────────────────┼──────────────────────────────┼─────────────────────────────────────────────────────────┤
│ PWDEBUG=1 │ PWDEBUG=1 pytest ... │ Opens Inspector GUI, forces headed mode, sets timeout=0.│
│ PWDEBUG=console │ PWDEBUG=console pytest ... │ Opens browser with standard DevTools console attached. │
│ page.pause() │ Python API Method │ Programmatic breakpoint; halts execution at line. │
│ playwright codegen <url> │ CLI Command │ Launches browser recorder; emits live Python code. │
│ Resume Execution │ F8 Key (or Play Button) │ Continues running script until next breakpoint or end. │
│ Step Over │ F10 Key (or Step Button) │ Advances execution by exactly ONE statement. │
│ Explore & Pick Locator │ GUI Toolbar Icon │ Hover over any element to generate resilient selector. │
│ playwright.$("selector") │ DevTools Console Method │ Tests Playwright selector engine query in live console. │
│ playwright.$$("selector") │ DevTools Console Method │ Returns array of all matching elements in active page. │
│ playwright.inspect("sel") │ DevTools Console Method │ Highlights element with Playwright inspection box. │
├──────────────────────────────┴──────────────────────────────┴─────────────────────────────────────────────────────────┤
│ PLAYWRIGHT ACTIONABILITY CHECKS OBSERVED IN INSPECTOR: │
│ * Attached: Element is present in the document DOM. │
│ * Visible: Element is not hidden (non-zero size, no opacity:0, no display:none). │
│ * Stable: Element is not animating or shifting coordinates. │
│ * Enabled: Element does not carry the 'disabled' attribute. │
│ * Editable: Element is not readonly (for text inputs and fills). │
│ * Receives Events: Element is not obscured by floating overlays, loaders, or modal backdrops. │
└───────────────────────────────────────────────────────────────────────────────────────────────────────────────────────┘