"""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()
本例需在 Windows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。 中运行,请复制源码、保存文件或下载工程包后在本地执行验证。
运行说明与环境独立工程
运行环境:Windows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。
入口文件:projects/playwright-debugging-lab/explore-debugging.py
本地运行步骤快速上手
- 点击上方“保存源码”保存为
explore-debugging.py,或下载右侧课程工程包。 - 确认本地已准备 Windows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。。
- 按对应章节命令执行,结合正文核对实际输出。
附件与关联工程包下载
课程关联工程包(登记关联39章) · 含当前章节或实例 · mbskycom202612a602.zip
课程关联工程包(登记关联1章) · 含当前章节或实例 · mbskycom202612a609.zip