"""Offline Playwright Chromium lab for Chapter 19: Playwright Waiting & Timeout."""
import json
import re
import threading
import time
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
from playwright.sync_api import sync_playwright, expect, TimeoutError as PwTimeoutError
START_HTML = """<!doctype html>
<html><head><meta charset='utf-8'><title>Wait Start</title></head>
<body>
<div id="host"></div>
<div id="status">初始</div>
<button id="go-dash" onclick="setTimeout(()=>location.href='/dashboard', 80)">前往仪表盘</button>
<button id="fetch-api" onclick="fetch('/api/data').then(r=>r.json()).then(d=>{document.getElementById('api-out').textContent=d.msg})">请求接口</button>
<div id="api-out"></div>
<button id="del-btn" onclick="window.__dlgResult=confirm('确认删除?')">删除</button>
<a id="new-win" href="/popup" target="_blank">新窗口打开</a>
<script>
setTimeout(() => {
const b = document.createElement('button');
b.id = 'late-btn';
b.textContent = '延迟出现的按钮';
b.disabled = true;
b.onclick = () => setTimeout(() => { document.getElementById('status').textContent = '数据加载完成'; }, 80);
document.getElementById('host').appendChild(b);
setTimeout(() => { b.disabled = false; }, 60);
}, 60);
setTimeout(() => {
const p = document.createElement('span');
p.id = 'slow-300';
p.textContent = 'SLOW_READY';
document.body.appendChild(p);
}, 300);
</script>
</body></html>
"""
DASH_HTML = """<!doctype html>
<html><head><meta charset='utf-8'><title>Dashboard</title></head>
<body>
<div id="ready-holder"></div>
<script>
setTimeout(() => {
const s = document.createElement('div');
s.id = 'ready-badge';
s.textContent = 'DASH_OK';
document.getElementById('ready-holder').appendChild(s);
window.__appReady = true;
}, 80);
</script>
</body></html>
"""
POPUP_HTML = "<!doctype html><html><head><meta charset='utf-8'><title>Popup Window</title></head><body><h1>Popup</h1></body></html>"
class WaitHandler(BaseHTTPRequestHandler):
def log_message(self, format, *args):
return
def _send(self, code, body, content_type="text/html; charset=utf-8"):
data = body.encode("utf-8") if isinstance(body, str) else body
self.send_response(code)
self.send_header("Content-Type", content_type)
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, START_HTML)
elif self.path == "/dashboard":
self._send(200, DASH_HTML)
elif self.path == "/popup":
self._send(200, POPUP_HTML)
elif self.path == "/api/data":
time.sleep(0.05)
self._send(200, json.dumps({"ok": True, "msg": "payload-200"}), "application/json; charset=utf-8")
else:
self._send(404, "not found")
def launch_browser(p):
for kwargs in (dict(channel="chrome", headless=True), dict(channel="msedge", headless=True), dict(headless=True)):
try:
return p.chromium.launch(**kwargs)
except Exception:
continue
raise RuntimeError("No local Chromium executable found")
def main():
server = ThreadingHTTPServer(("127.0.0.1", 0), WaitHandler)
port = server.server_address[1]
base_url = f"http://127.0.0.1:{port}"
thread = threading.Thread(target=server.serve_forever, daemon=True)
thread.start()
cases = []
try:
with sync_playwright() as p:
browser = launch_browser(p)
# Case 1: Three-layer auto-wait (Locator + Actionability + Assertion auto-retry)
ctx1 = browser.new_context()
pg1 = ctx1.new_page()
pg1.goto(f"{base_url}/")
btn = pg1.get_by_role("button", name="延迟出现的按钮")
btn.click()
expect(pg1.get_by_text("数据加载完成")).to_be_visible()
status_text = pg1.locator("#status").text_content()
ctx1.close()
actual1 = {"status_text": status_text}
expected1 = {"status_text": "数据加载完成"}
cases.append(dict(name="three_layer_auto_wait", expected=expected1, actual=actual1, passed=actual1 == expected1))
# Case 2: Manual waits (wait_for_url, wait_for_load_state, wait_for_selector, wait_for_function)
ctx2 = browser.new_context()
pg2 = ctx2.new_page()
pg2.goto(f"{base_url}/")
pg2.click("#go-dash")
pg2.wait_for_url(re.compile(r"/dashboard$"))
pg2.wait_for_load_state("domcontentloaded")
pg2.wait_for_load_state("load")
pg2.wait_for_load_state("networkidle")
badge_el = pg2.wait_for_selector("#ready-badge")
pg2.wait_for_function("() => window.__appReady === true")
badge_text = badge_el.text_content()
dash_url_ok = pg2.url.endswith("/dashboard")
ctx2.close()
actual2 = {"dash_url_ok": dash_url_ok, "badge_text": badge_text}
expected2 = {"dash_url_ok": True, "badge_text": "DASH_OK"}
cases.append(dict(name="manual_waits_url_load_selector_function", expected=expected2, actual=actual2, passed=actual2 == expected2))
# Case 3: wait_for_response, dialog event, and context popup page event
ctx3 = browser.new_context()
pg3 = ctx3.new_page()
pg3.goto(f"{base_url}/")
with pg3.expect_response(lambda r: "/api/data" in r.url and r.status == 200) as resp_info:
pg3.click("#fetch-api")
api_data = resp_info.value.json()
dialog_msg = []
def handle_dialog(d):
dialog_msg.append(d.message)
d.accept()
pg3.once("dialog", handle_dialog)
pg3.click("#del-btn")
dlg_accepted = pg3.evaluate("() => window.__dlgResult")
with ctx3.expect_page() as new_pg_info:
pg3.get_by_role("link", name="新窗口打开").click()
new_pg = new_pg_info.value
new_pg.wait_for_load_state("domcontentloaded")
popup_title = new_pg.title()
ctx3.close()
actual3 = {
"api_msg": api_data["msg"],
"dialog_msg": dialog_msg[0],
"dialog_accepted": dlg_accepted,
"popup_title": popup_title,
}
expected3 = {
"api_msg": "payload-200",
"dialog_msg": "确认删除?",
"dialog_accepted": True,
"popup_title": "Popup Window",
}
cases.append(dict(name="wait_for_response_dialog_and_popup", expected=expected3, actual=actual3, passed=actual3 == expected3))
# Case 4: Timeout precedence (per-call > page default) and TimeoutError handling
ctx4 = browser.new_context()
pg4 = ctx4.new_page()
pg4.set_default_navigation_timeout(5000)
pg4.set_default_timeout(150)
pg4.goto(f"{base_url}/")
default_timed_out = False
try:
pg4.locator("#missing-control").click()
except PwTimeoutError:
default_timed_out = True
# Per-call timeout=2000 overrides the 150ms default and waits for the 300ms element
slow_text = pg4.locator("#slow-300").text_content(timeout=2000)
ctx4.close()
actual4 = {"default_timeout_raised": default_timed_out, "per_call_override_text": slow_text}
expected4 = {"default_timeout_raised": True, "per_call_override_text": "SLOW_READY"}
cases.append(dict(name="timeout_hierarchy_and_exception_handling", expected=expected4, actual=actual4, passed=actual4 == expected4))
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-waiting-timeout-lab/explore-waiting-timeout.py
本地运行步骤快速上手
- 点击上方“保存源码”保存为
explore-waiting-timeout.py,或下载右侧课程工程包。 - 确认本地已准备 Windows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。。
- 按对应章节命令执行,结合正文核对实际输出。
附件与关联工程包下载
课程关联工程包(登记关联1章) · 含当前章节或实例 · mbskycom202612a637.zip
课程关联工程包(登记关联39章) · 含当前章节或实例 · mbskycom202612a602.zip