"""Offline Playwright lab for Chapter 07 (first-test): goto waitUntil/referer, expect auto-retry, APIRequestContext, expected failure capture, async/await."""
import asyncio
import http.server
import json
import os
import re
import threading
from playwright.async_api import async_playwright
from playwright.sync_api import expect, sync_playwright
INDEX_HTML = """<!doctype html>
<html lang="zh-CN">
<head><meta charset="utf-8"><title>初始标题</title></head>
<body>
<h1 id="banner" style="display:none">BlueSky Playwright 首页</h1>
<div id="api-status">loading</div>
<script>
fetch('/api/ping').then(r => r.json()).then(d => {
document.getElementById('api-status').textContent = d.ok ? 'ok' : 'fail';
});
setTimeout(() => {
document.title = 'BlueSky Playwright 测试首页';
document.getElementById('banner').style.display = 'block';
}, 120);
</script>
</body>
</html>"""
class _Handler(http.server.BaseHTTPRequestHandler):
last_referer = ""
def do_GET(self):
if self.path == "/api/ping":
data = json.dumps({"ok": True, "service": "local-test"}).encode("utf-8")
self.send_response(200)
self.send_header("Content-Type", "application/json")
self.send_header("Content-Length", str(len(data)))
self.end_headers()
self.wfile.write(data)
return
_Handler.last_referer = self.headers.get("Referer", "")
data = INDEX_HTML.encode("utf-8")
self.send_response(200)
self.send_header("Content-Type", "text/html; charset=utf-8")
self.send_header("Content-Length", str(len(data)))
self.end_headers()
self.wfile.write(data)
def log_message(self, format, *args):
pass
def launch_browser_sync(p):
exe = p.chromium.executable_path
if exe and os.path.exists(exe):
return p.chromium.launch(headless=True)
for ch in ("chrome", "msedge"):
try:
return p.chromium.launch(channel=ch, headless=True)
except Exception:
continue
return p.chromium.launch(headless=True)
async def run_async_case(base_url: str):
async with async_playwright() as p:
exe = p.chromium.executable_path
if exe and os.path.exists(exe):
browser = await p.chromium.launch(headless=True)
else:
browser = await p.chromium.launch(channel="chrome", headless=True)
page = await browser.new_page()
await page.goto(f"{base_url}/", wait_until="load")
await page.wait_for_function("() => document.title.includes('Playwright')")
title = await page.title()
await browser.close()
return title
def main():
server = http.server.ThreadingHTTPServer(("127.0.0.1", 0), _Handler)
port = server.server_address[1]
threading.Thread(target=server.serve_forever, daemon=True).start()
base_url = f"http://127.0.0.1:{port}"
cases = []
try:
with sync_playwright() as p:
browser = launch_browser_sync(p)
ctx = browser.new_context()
page = ctx.new_page()
# Case 1: page.goto waitUntil modes + custom Referer header
page.goto(f"{base_url}/", wait_until="domcontentloaded", timeout=10000, referer="http://127.0.0.1/origin-ref")
ref_seen = _Handler.last_referer
page.goto(f"{base_url}/", wait_until="load", timeout=10000)
page.goto(f"{base_url}/", wait_until="networkidle", timeout=10000)
api_status = page.locator("#api-status").inner_text()
exp1 = {"referer_received": "http://127.0.0.1/origin-ref", "networkidle_api_status": "ok"}
act1 = {"referer_received": ref_seen, "networkidle_api_status": api_status}
cases.append(dict(name="goto_wait_until_and_referer", expected=exp1, actual=act1, passed=act1 == exp1))
# Case 2: expect() auto-retry on delayed title & visibility + URL assertion
page.goto(f"{base_url}/", wait_until="domcontentloaded")
expect(page).to_have_title(re.compile("Playwright"))
expect(page).to_have_url(f"{base_url}/")
expect(page.get_by_text("BlueSky Playwright 首页")).to_be_visible()
exp2 = {"title_matched": True, "url_matched": True, "banner_visible": True}
act2 = {
"title_matched": "Playwright" in page.title(),
"url_matched": page.url == f"{base_url}/",
"banner_visible": page.get_by_text("BlueSky Playwright 首页").is_visible(),
}
cases.append(dict(name="expect_auto_retry_assertions", expected=exp2, actual=act2, passed=act2 == exp2))
# Case 3: APIRequestContext (matching request fixture)
req_ctx = p.request.new_context(base_url=base_url)
resp = req_ctx.get("/api/ping")
payload = resp.json()
req_ctx.dispose()
exp3 = {"status": 200, "ok": True, "service": "local-test"}
act3 = {"status": resp.status, "ok": payload["ok"], "service": payload["service"]}
cases.append(dict(name="api_request_context_fixture", expected=exp3, actual=act3, passed=act3 == exp3))
# Case 4: Deliberate assertion failure + diagnostic screenshot
failed_as_expected = False
try:
expect(page).to_have_title(re.compile("不存在的文字"), timeout=300)
except AssertionError as exc:
failed_as_expected = "Page title expected to match" in str(exc) or "不存在的文字" in str(exc)
err_png = page.screenshot()
exp4 = {"failed_as_expected": True, "captured_error_png": True}
act4 = {"failed_as_expected": failed_as_expected, "captured_error_png": err_png[:8] == b"\x89PNG\r\n\x1a\n"}
cases.append(dict(name="expected_assertion_failure_capture", expected=exp4, actual=act4, passed=act4 == exp4))
ctx.close()
browser.close()
# Case 5: async/await API execution
async_title = asyncio.run(run_async_case(base_url))
exp5 = {"async_title": "BlueSky Playwright 测试首页"}
act5 = {"async_title": async_title}
cases.append(dict(name="async_playwright_await_mode", expected=exp5, actual=act5, passed=act5 == exp5))
finally:
server.shutdown()
server.server_close()
print(json.dumps({"cases": cases}, ensure_ascii=False, indent=2))
if __name__ == "__main__":
main()
本例需在 Windows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。 中运行,请复制源码、保存文件或下载工程包后在本地执行验证。
运行说明与环境独立工程
运行环境:Windows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。
入口文件:projects/playwright-first-test-lab/explore-first-test.py
本地运行步骤快速上手
- 点击上方“保存源码”保存为
explore-first-test.py,或下载右侧课程工程包。 - 确认本地已准备 Windows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。。
- 按对应章节命令执行,结合正文核对实际输出。
附件与关联工程包下载
课程关联工程包(登记关联39章) · 含当前章节或实例 · mbskycom202612a602.zip
课程关联工程包(登记关联1章) · 含当前章节或实例 · mbskycom202612a614.zip