蓝色天空网mbsky.com · 知识 · 实践 · 创造Playwright · 本地阅读预览
教程 / AI / 智能开发 / Playwright

Playwright 调试工具

核对 Playwright 三大调试工具(UI Mode、Trace Viewer、--debug 与 page.pause())的功能分工及 Trace 压缩包内部结构实测。

本站独立整理的内容草稿。实例显示的是预期结果;浏览器、服务端运行与技术内容验收尚待完成,本页只用于阅读和图文核对。

学完这一章,你能够

UI Mode 图形化交互调试

Playwright 内置三套互补的调试利器:面向日常开发的 UI Mode、面向离线深度回放的 Trace Viewer,以及面向断点单步排查的 `--debug` 与 `page.pause()`。运行 `npx playwright test --ui` 即可进入一站式图形界面。

在 UI Mode 左侧测试树中可展开各个文件与 `describe` 分组,按需单独运行或调试某条用例;开启 Watch Mode(监听模式)后,只要测试脚本或应用源码发生改动,受影响的用例便会自动重跑。

执行完成后,顶部时间轴视图(Timeline)会用不同色块标出页面导航与交互动作,悬停即可预览对应时刻画面,双击可框选区间查看细粒度日志;点击任意步骤时,右侧实时呈现可检查的 DOM Snapshot,直观对比操作前后页面结构差异。本站离线在本地服务上实测点击按钮触发异步拉取前后,DOM 状态准确由 `#status='idle'`、0 条列表项变为 `#status='submitted'`、1 条列表项。

当套件规模较大时,UI Mode 支持按测试名称搜索、按 `@tag` 标签筛选、按 Project 筛选,以及按通过(passed)、失败(failed)、跳过(skipped)状态快速定位目标用例。

Trace Viewer 深度回放与归档实测

Trace Viewer 就像测试运行的黑匣子录像机,允许事后逐帧复盘每一步执行现场。在 `playwright.config.ts` 的 `use.trace` 中可选择 `'off'`、`'on'`、`'on-first-retry'`(推荐,仅首次重试时录制以兼顾性能)或 `'retain-on-failure'`(仅失败时保留)。生成的压缩包既可用 `npx playwright show-trace path/to/trace.zip` 在本地打开,也可拖拽到官方 `trace.playwright.dev` 在线查看。

本站离线开启 `context.tracing.start(screenshots=True, snapshots=True)` 驱动本地页面完成导航、点击、请求 `/api/status` 与控制台输出,随后解析生成的 `full-trace.zip`:压缩包内真实记录了 `frame-snapshot` DOM 快照、`before`/`after` 操作事件、`trace.network` 中 `/api/status` 返回 HTTP `200` 的请求记录、`button clicked` 控制台事件以及 `screencast/` 截图帧。进一步使用 `start_chunk()` / `stop_chunk()` 模拟 `'retain-on-failure'` 策略:通过的测试不落盘,失败的测试准确生成非空 `fail-trace.zip`。因此当 CI 出现本地难以复现的故障时,下载 Trace 文件即可离线还原现场。

--debug 命令行模式、page.pause() 与选型

执行 `npx playwright test --debug` 会自动拉起 Playwright Inspector 窗口并进入有头单步模式:可逐条步进执行操作、打开浏览器 DevTools 检查样式与网络,并使用 `F10`(Step Over)与 `F11`(Step Into)精准控制调试节奏。

若只想停在某条用例的关键步骤处检查状态,可在脚本中插入 `await page.pause()` 作为显式断点,运行至该行时同样会唤起 Inspector 供交互查看。此外在无头脚本中结合 `page.on('console')` 与 `page.on('pageerror')` 也能自动捕获运行时异常——本站实测成功截获 `['info', 'debug-init']`、`['error', 'api-timeout']` 及未捕获异常 `uncaught-crash`。三种调试手段的适用场景见下表对比。

Trace 文件包含的核心调试信息

内容说明
DOM 快照记录每一步操作执行前后的完整可交互页面 DOM 快照(实测对应 `frame-snapshot` 事件)
网络请求记录全部 HTTP 请求与响应的 URL、状态码、请求头和响应体(实测写入 `trace.network`)
控制台日志收集页面输出的所有 `console` 级别消息与运行时错误
截图按时间线保存操作过程画面帧(实测归档于 `screencast/` 目录)
操作记录记录每个 Playwright API 的调用参数、起止时间与等待日志(实测 `before`/`after` 事件)
源代码开启 `sources: true` 时关联每一步操作对应的测试源码行号

Playwright 三种调试方式选型对比

方式适用场景
UI Mode日常本地开发,可视化浏览测试树、开启 Watch 自动重跑与快速查看状态
Trace Viewer排查 CI 离线失败、深度回溯复杂用例每一步的 DOM/网络/日志证据
`--debug` / `page.pause()`编写新测试或针对特定步骤设置断点,配合 Inspector 与 DevTools 单步排错

运行 Trace 归档结构解析、失败保留分块、DOM 前后对比与错误监听实测

python · 阅读源码
"""Offline Playwright Chromium lab for Chapter 25: Debugging Tools."""
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
import json
import os
from pathlib import Path
import tempfile
import threading
import zipfile
from playwright.sync_api import sync_playwright


DEBUG_HTML = """<!doctype html>
<html lang="zh-CN">
<head><meta charset="utf-8"><title>Debug Demo</title></head>
<body>
  <button id="load-btn">加载状态</button>
  <p id="status">idle</p>
  <ul id="log-list"></ul>
  <script>
    document.getElementById('load-btn').addEventListener('click', async () => {
      console.log('button clicked');
      const r = await fetch('/api/status');
      const d = await r.json();
      document.getElementById('status').textContent = d.state;
      const li = document.createElement('li');
      li.textContent = 'step:' + d.state;
      document.getElementById('log-list').appendChild(li);
    });
  </script>
</body>
</html>"""


class DebugHandler(BaseHTTPRequestHandler):
    def log_message(self, fmt, *args):
        pass

    def _send(self, code, body, ctype="text/html; charset=utf-8"):
        data = body.encode("utf-8")
        self.send_response(code)
        self.send_header("Content-Type", ctype)
        self.send_header("Content-Length", str(len(data)))
        self.end_headers()
        self.wfile.write(data)

    def do_GET(self):
        if self.path == "/":
            self._send(200, DEBUG_HTML)
        elif self.path == "/api/status":
            self._send(200, '{"state":"submitted","code":200}', "application/json")
        else:
            self._send(404, "not found", "text/plain")


def launch_chromium(p):
    if os.path.exists(p.chromium.executable_path):
        return p.chromium.launch(headless=True)
    for ch in ("chrome", "msedge"):
        try:
            return p.chromium.launch(channel=ch, headless=True)
        except Exception:
            continue
    raise RuntimeError("No Chromium/Chrome/Edge browser executable available")


def make_case(name, expected, actual):
    return {"name": name, "expected": expected, "actual": actual, "passed": actual == expected}


def main():
    server = ThreadingHTTPServer(("127.0.0.1", 0), DebugHandler)
    port = server.server_address[1]
    base = f"http://127.0.0.1:{port}"
    thread = threading.Thread(target=server.serve_forever, daemon=True)
    thread.start()

    cases = []
    try:
        with tempfile.TemporaryDirectory() as tmpdir:
            with sync_playwright() as p:
                browser = launch_chromium(p)
                try:
                    # Case 1: Full Trace Viewer archive inspection (DOM snapshots, network, console, screenshots, actions)
                    trace_path = Path(tmpdir) / "full-trace.zip"
                    ctx = browser.new_context(base_url=base)
                    ctx.tracing.start(screenshots=True, snapshots=True, sources=False)
                    pg = ctx.new_page()
                    pg.goto("/")
                    with pg.expect_response("**/api/status"):
                        pg.locator("#load-btn").click()
                    pg.wait_for_function("() => document.getElementById('status').textContent === 'submitted'")
                    ctx.tracing.stop(path=str(trace_path))
                    ctx.close()

                    with zipfile.ZipFile(trace_path) as zf:
                        names = zf.namelist()
                        trace_events = [
                            json.loads(line)
                            for line in zf.read("trace.trace").decode("utf-8").splitlines()
                            if line.strip()
                        ]
                        net_events = [
                            json.loads(line)
                            for line in zf.read("trace.network").decode("utf-8").splitlines()
                            if line.strip()
                        ]

                    event_types = {e.get("type") for e in trace_events}
                    has_api_net = any(
                        "/api/status" in e.get("snapshot", {}).get("request", {}).get("url", "")
                        and e.get("snapshot", {}).get("response", {}).get("status") == 200
                        for e in net_events
                    )
                    has_console_event = any(
                        e.get("type") == "console" and "button clicked" in e.get("text", "")
                        for e in trace_events
                    )
                    cases.append(make_case(
                        "trace_zip_artifact_contents",
                        {
                            "has_frame_snapshot": True,
                            "has_before_after_actions": True,
                            "has_api_network_200": True,
                            "has_console_log": True,
                            "has_screencast_frames": True,
                        },
                        {
                            "has_frame_snapshot": "frame-snapshot" in event_types,
                            "has_before_after_actions": {"before", "after"}.issubset(event_types),
                            "has_api_network_200": has_api_net,
                            "has_console_log": has_console_event,
                            "has_screencast_frames": any(n.startswith("screencast/") for n in names),
                        },
                    ))

                    # Case 2: retain-on-failure trace chunking policy
                    pass_zip = Path(tmpdir) / "pass-trace.zip"
                    fail_zip = Path(tmpdir) / "fail-trace.zip"
                    ctx2 = browser.new_context(base_url=base)
                    ctx2.tracing.start(screenshots=True, snapshots=True)

                    # Run 1 (passing) -> discard chunk
                    ctx2.tracing.start_chunk()
                    pg2 = ctx2.new_page()
                    pg2.goto("/")
                    ok_pass = pg2.locator("#status").text_content() == "idle"
                    ctx2.tracing.stop_chunk(path=None if ok_pass else str(pass_zip))

                    # Run 2 (simulated failure) -> persist chunk
                    ctx2.tracing.start_chunk()
                    pg2.locator("#load-btn").click()
                    pg2.wait_for_function("() => document.getElementById('status').textContent === 'submitted'")
                    ok_fail = pg2.locator("#status").text_content() == "expected_other"
                    ctx2.tracing.stop_chunk(path=None if ok_fail else str(fail_zip))

                    ctx2.tracing.stop()
                    ctx2.close()
                    cases.append(make_case(
                        "trace_retain_on_failure_simulation",
                        {"pass_zip_exists": False, "fail_zip_exists": True, "fail_zip_nonempty": True},
                        {
                            "pass_zip_exists": pass_zip.exists(),
                            "fail_zip_exists": fail_zip.exists(),
                            "fail_zip_nonempty": fail_zip.exists() and fail_zip.stat().st_size > 0,
                        },
                    ))

                    # Case 3: DOM state before/after step inspection
                    ctx3 = browser.new_context(base_url=base)
                    pg3 = ctx3.new_page()
                    pg3.goto("/")
                    before_status = pg3.locator("#status").text_content()
                    before_items = pg3.locator("#log-list li").count()
                    with pg3.expect_response("**/api/status"):
                        pg3.locator("#load-btn").click()
                    pg3.wait_for_function("() => document.getElementById('status').textContent === 'submitted'")
                    after_status = pg3.locator("#status").text_content()
                    after_items = pg3.locator("#log-list li").count()
                    ctx3.close()
                    cases.append(make_case(
                        "dom_snapshot_before_after_action",
                        {"before_status": "idle", "before_items": 0, "after_status": "submitted", "after_items": 1},
                        {"before_status": before_status, "before_items": before_items, "after_status": after_status, "after_items": after_items},
                    ))

                    # Case 4: Console + uncaught pageerror diagnostics
                    ctx4 = browser.new_context()
                    pg4 = ctx4.new_page()
                    logs = []
                    errs = []
                    pg4.on("console", lambda m: logs.append((m.type, m.text)))
                    pg4.on("pageerror", lambda e: errs.append(str(e)))
                    pg4.set_content("""<script>
                        console.info('debug-init');
                        console.error('api-timeout');
                        setTimeout(() => { throw new Error('uncaught-crash'); }, 10);
                    </script>""")
                    pg4.wait_for_timeout(80)
                    ctx4.close()
                    cases.append(make_case(
                        "console_and_pageerror_capture",
                        {
                            "console_events": [["info", "debug-init"], ["error", "api-timeout"]],
                            "has_pageerror": True,
                        },
                        {
                            "console_events": [[t, txt] for t, txt in logs],
                            "has_pageerror": any("uncaught-crash" in e for e in errs),
                        },
                    ))
                finally:
                    browser.close()
    finally:
        server.shutdown()
        server.server_close()

    print(json.dumps({"cases": cases}, ensure_ascii=False))


if __name__ == "__main__":
    main()
预期结果 · 待实际运行核验
  • 核对 trace.zip 包含 DOM 快照/网络 200/控制台/截图/操作事件、retain-on-failure 仅失败写盘、DOM 变更前后差异及 pageerror 捕获。
运行 Trace 归档结构解析、失败保留分块、DOM 前后对比与错误监听实测

所需环境:Windows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。

当前源码 SHA256:a44ebe9dcb034a143d932c5af0411fab89fe96cdf030e917b13e61f93faf2e6f

下载本站示例源码

本地运行

解压后按 README 说明在对应本地环境运行脚本。

下载Playwright 调试工具实验

所需环境:Windows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。

ZIP SHA256:afc76a9fe5ecd7da73fe4c16fa37cd36b006bcfd7a3017e484a915cbfcc20539

常见错误与边界

  • 实际端口、文档资源与应用配置都应和测试条件一致。

练习与解答

在 CI 环境中为什么通常推荐使用 trace: 'on-first-retry' 或 'retain-on-failure',而不是 trace: 'on'?

展开参考解答

trace: 'on' 会为每条通过和失败的用例都录制完整 DOM 快照与截图帧,显著增加运行耗时和制品体积;改为 'on-first-retry' 或 'retain-on-failure' 既能在用例真正失败时拿到完整回放证据,又避免了全量录制的开销。

规范与官方依据