PLAYWRIGHT INSPECTOR & INTERACTIVE DEBUGGING

Master live breakpoint debugging, selector discovery, and step-by-step execution in Playwright with Python: PWDEBUG environmental execution, page.pause() breakpoints, interactive locator query evaluation, live recording with Codegen, DevTools console integration, and troubleshooting flaky locators in real time.

🛠️ 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()).

1. Playwright Inspector Architecture & Control Topology
When Inspector mode is engaged, Playwright switches the browser to headed execution, sets timeouts to infinite, and connects an interactive GUI that intercepts every action command before execution.
Playwright Inspector Debugging Architecture
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  │
└───────────────────────────────────────────────────────────────────────────────┘
Architectural Advantage: Complete elimination of blind trial-and-error debugging. Inspect the live DOM tree at any failure point, test alternative locator expressions interactively, and verify auto-waiting state before stepping.
Real-Time Example 1: Programmatic Breakpoint via page.pause()
Place page.pause() inside any Playwright Python script. Execution freezes at that exact line, opening the Inspector GUI so you can step through subsequent actions.
Python (Programmatic page.pause Breakpoint)
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()
Output: Execution paused at breakpoint. Inspecting live browser state... [Playwright Inspector Window Opened] * Current Statement Highlighted: todo_item = page.locator(".todo-list li").first * Interactive Controls: [Resume F8] [Step Over F10] [Record] [Explore]
Real-Time Example 2: CLI Environmental Debugging with PWDEBUG=1
Launch your entire Pytest suite or standalone scripts under Inspector mode without modifying any source code using the PWDEBUG=1 environment variable.
Bash / Terminal CLI Debugging Commands
# 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
CLI Value: PWDEBUG=1 pauses execution on the very first Playwright action, disables test timeouts, and opens the Inspector alongside the browser window automatically.
Real-Time Example 3: Live Selector Discovery via "Explore & Pick Locator"
Use the Inspector's "Explore" button to hover over web elements and discover resilient Playwright locators that prioritize user-facing accessibility roles over brittle CSS classes.
Python (Testing Discovered Locators Live)
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()
Discovered Selectors via Inspector: 1. Hover on Input ──► page.get_by_placeholder("Enter corporate client") 2. Hover on Button ──► page.get_by_role("button", name="Submit Invoice Ledger") Matching element count: 1 element highlighted in live browser!
Real-Time Example 4: Evaluating Selectors via Browser DevTools (playwright.$)
When Inspector pauses execution, Playwright injects the playwright object into the browser's Developer Tools Console, enabling live interactive querying of selector engines.
JavaScript (DevTools Console Queries)
// 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: 
DevTools Diagnostic Value: Verify whether your locator matches 0 elements, 1 unique element, or multiple ambiguous elements before committing code changes to your repository.
Real-Time Example 5: Interactive Code Generation via Playwright Codegen
Use playwright codegen to record manual browser clicks, keystrokes, and assertions in real time, emitting idiomatic, clean Python Playwright code instantly.
Terminal / Shell Codegen Commands
# 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
Sample Codegen Output (tests/test_recorded_checkout.py): from playwright.sync_api import Playwright, sync_playwright, expect def run(playwright: Playwright) -> None: browser = playwright.chromium.launch(headless=False) context = browser.new_context() page = context.new_page() page.goto("https://demo.playwright.dev/todomvc/") page.get_by_placeholder("What needs to be done?").fill("Verify Playwright Inspector") page.get_by_placeholder("What needs to be done?").press("Enter") page.locator(".todo-list li").filter(has_text="Verify Playwright Inspector").get_by_role("checkbox").check() context.close() browser.close()
Real-Time Example 6: Conditional Debugging on Failure Hook in conftest.py
Automatically open the Playwright Inspector and pause execution only when an assertion or action fails, allowing you to debug the failure state while the browser is still open.
Python (conftest.py Auto-Pause on Failure Hook)
# 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
Output (When Test Fails): FAILED tests/test_billing.py::test_invoice_generation - TimeoutError [Inspector Hook] Test 'test_invoice_generation' failed! Freezing browser for interactive inspection... [Browser Remains Open and Inspector Halts on Failed State for Live Debugging]
Real-Time Example 7: Debugging Network Interceptions & Route Mocking Live
Pause execution to observe dynamic network routes configured via page.route(), inspecting headers and status codes in real time inside the browser while stepping through your test.
Python (Stepping Through Route Interceptions)
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()
Debugging Workflow: 1. Breakpoint 1: Inspect registered routes in console via playwright.routes() 2. Click 'Step Over' (F10): Watch #refresh-btn click execute live 3. Breakpoint 2: Observe DOM update (#bal updated to ₹ 2,500,000)
Real-Time Example 8: Debugging Auto-Waiting Timeouts and Actionability Checks
When a locator times out, use the Inspector to see which specific actionability check (attached, visible, stable, enabled, editable) is blocking the interaction.
Python (Diagnosing Actionability Check Failures)
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
Inspector Actionability Log: locator.click: waiting for locator("#activate-license") - locator resolved to - element is visible, stable, receives events - element is NOT enabled - waiting for element to become enabled... [User checks checkbox in live browser] - element became enabled! Performing click action.
Real-Time Example 9: Playwright Inspector Reference & CLI Options Matrix
A comprehensive reference summary of environment variables, GUI shortcuts, DevTools console helpers, and CLI commands for interactive Playwright debugging.
Inspector & Debugging Reference Matrix
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.                         │
└───────────────────────────────────────────────────────────────────────────────────────────────────────────────────────┘
Engineering Best Practice: Use page.pause() for rapid local development when authoring new complex flows. For CI failures, download the trace.zip and inspect it with Trace Viewer, reserving live Inspector debugging for local interactive triage.