Playwright Codegen
核对 Playwright Codegen 交互式录制流程、五类自动录制动作、八级最佳 Locator 优先级、四类断言生成及常用命令行仿真选项。
学完这一章,你能够
- 核对 Playwright Codegen 交互式录制流程、五类自动录制动作、八级最佳 Locator 优先级、四类断言生成及常用命令行仿真选项。
Codegen 定位与启动方式
Codegen(Code Generator)是 Playwright 内置的交互式测试录制器:测试人员像普通用户一样在页面点击、输入或切换选项,工具会同步把每一步交互实时翻译成规范的 Playwright 代码。
通过命令行执行 `npx playwright codegen <URL>` 即可启动(支持通过 `--target=javascript`、`--target=python` 等参数切换目标语言,默认为 TypeScript)。启动后会同时弹出两个窗口:一个是供直接交互的浏览器窗口,另一个是实时输出并可复制脚本的 Playwright Inspector 窗口。
五类常见录制操作与回放核对
在录制窗口中的常规交互都会映射为标准 API:地址栏跳转生成 `page.goto()`;点击按钮、链接或菜单生成 `page.getByRole(...).click()`;输入框键入文字生成 `page.getByLabel(...).fill(...)` 或 `page.getByPlaceholder(...).fill(...)`;下拉框切换选项生成 `page.getByLabel(...).selectOption(...)`;勾选或取消复选框则生成 `.check()` 与 `.uncheck()`。本站离线在真实无头 Chromium 中按上述五类动作顺序回放本地表单页:`fill('alice')`、`select_option('editor')`、`check()`/`uncheck()` 状态切换及按钮点击均准确生效,页面状态标签更新为 `alice:editor`。
Locator 自动优选顺序与四类断言
为了生成抗改版、贴近用户感知的定位器,Codegen 按明确优先级评估元素属性:首选具备 ARIA 语义的 `getByRole()`,其次依次为 `getByText()`、`getByLabel()`、`getByPlaceholder()`、`getByAltText()`、`getByTestId()`、`getByTitle()`,仅当语义属性都缺失时才回退到 CSS 选择器 `locator()`。若初步定位匹配到多个节点,Codegen 会自动补充过滤条件直至唯一锁定目标。本站离线页面同时布置这 8 类元素,实测全部 8 种定位策略均唯一解析(`count() == 1`)。
借助 Inspector 工具栏的断言按钮,无需手写即可直接插入四类断言:`Assert Visibility` 生成 `await expect(locator).toBeVisible()`,`Assert Text` 生成 `await expect(locator).toHaveText(...)`,`Assert Value` 生成 `await expect(locator).toHaveValue(...)`,`Assert Snapshot` 生成 `await expect(locator).toHaveScreenshot()`。本站实测前三种 DOM 断言与元素 PNG 截图采集均通过。
常用命令行选项与录制方式对比
命令行启动 Codegen 时可叠加多语言输出、保存/加载认证状态、指定输出文件以及移动端视口/设备/深色模式仿真选项。本站实测复现上述上下文参数:`viewport=375×812`、`color_scheme='dark'` 与加载预存 `auth.json` 后,页面精确呈现深色模式并恢复会话 Cookie `rec_session=saved42`,且内置 `iPhone 15` 预设视口为 `393×659`。日常开发可结合团队习惯在命令行 Codegen 与 VS Code 插件录制之间选择。
Codegen 常用命令行选项
| 选项 | 说明 |
|---|---|
| `--target=javascript` | 生成 JavaScript 代码(默认输出 TypeScript) |
| `--target=python` | 生成 Python Playwright 代码 |
| `--target=java` | 生成 Java Playwright 代码 |
| `--target=csharp` | 生成 C# / .NET Playwright 代码 |
| `--save-storage=auth.json` | 录制结束后自动将登录态 Cookie/localStorage 保存至指定文件 |
| `--load-storage=auth.json` | 先加载已有认证状态文件再进入页面录制,免去重复登录 |
| `-o tests/test.spec.ts` | 将录制代码直接写入指定文件而非仅输出到终端 |
| `--viewport-size=375,812` | 自定义录制视口尺寸(如 375×812 移动端尺寸) |
| `--device="iPhone 15"` | 套用内置设备预设进行仿真录制(实测 `iPhone 15` 视口 393×659) |
| `--color-scheme=dark` | 指定录制环境颜色方案为深色模式 |
Codegen 命令行与 VS Code 插件录制对比
| 方式 | 适用场景 |
|---|---|
| VS Code Record New | 日常 TypeScript/JS 套件开发,录制代码直接写入当前编辑器并即时微调 |
| Codegen 命令行 | 快速原型验证、多语言代码生成(Python/Java/C#)或不依赖特定 IDE 的场景 |
运行五类录制动作回放、八级定位优先级、断言验证与仿真选项实测
"""Offline Playwright Chromium lab for Chapter 26: Codegen."""
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
from http.cookies import SimpleCookie
import json
import os
from pathlib import Path
import tempfile
import threading
from playwright.sync_api import sync_playwright, expect
CODEGEN_HTML = """<!doctype html>
<html lang="zh-CN">
<head><meta charset="utf-8"><title>Codegen Target</title></head>
<body>
<h1 id="heading">测试录制页</h1>
<p>欢迎使用录制功能</p>
<form id="demo-form">
<label for="user-input">用户名</label>
<input id="user-input" placeholder="请输入用户名" />
<input id="note-input" placeholder="请输入备注" />
<label for="role-select">角色</label>
<select id="role-select">
<option value="viewer">访客</option>
<option value="editor">编辑</option>
</select>
<label><input id="agree-box" type="checkbox" /> 同意协议</label>
<button type="button" id="submit-btn">提交</button>
</form>
<img alt="产品图标" src="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mNk+A8AAQUBAScY42YAAAAASUVORK5CYII=" />
<div data-testid="status-badge" title="状态提示">未提交</div>
<span class="css-fallback">尾部节点</span>
<script>
document.getElementById('submit-btn').addEventListener('click', () => {
const u = document.getElementById('user-input').value;
const r = document.getElementById('role-select').value;
document.querySelector('[data-testid="status-badge"]').textContent = u + ':' + r;
});
</script>
</body>
</html>"""
class CodegenHandler(BaseHTTPRequestHandler):
def log_message(self, fmt, *args):
pass
def _send(self, code, body, extra_headers=None):
data = body.encode("utf-8")
self.send_response(code)
self.send_header("Content-Type", "text/html; charset=utf-8")
self.send_header("Content-Length", str(len(data)))
for k, v in (extra_headers or []):
self.send_header(k, v)
self.end_headers()
self.wfile.write(data)
def do_GET(self):
if self.path == "/":
self._send(200, CODEGEN_HTML, [("Set-Cookie", "rec_session=saved42; Path=/")])
elif self.path == "/whoami":
ck = SimpleCookie()
ck.load(self.headers.get("Cookie", ""))
val = ck["rec_session"].value if "rec_session" in ck else "none"
self._send(200, f"<span id='sess'>{val}</span>")
else:
self._send(404, "not found")
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), CodegenHandler)
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:
auth_file = Path(tmpdir) / "auth.json"
with sync_playwright() as p:
browser = launch_chromium(p)
try:
# Case 1: Replay canonical Codegen recorded actions (goto, fill, selectOption, check/uncheck, click)
ctx = browser.new_context(base_url=base)
pg = ctx.new_page()
pg.goto("/")
pg.get_by_label("用户名").fill("alice")
pg.get_by_placeholder("请输入备注").fill("note-1")
pg.get_by_label("角色").select_option("editor")
pg.get_by_label("同意协议").check()
checked_after_check = pg.get_by_label("同意协议").is_checked()
pg.get_by_label("同意协议").uncheck()
checked_after_uncheck = pg.get_by_label("同意协议").is_checked()
pg.get_by_role("button", name="提交").click()
badge_text = pg.get_by_test_id("status-badge").text_content()
ctx.storage_state(path=str(auth_file))
cases.append(make_case(
"recorded_user_actions_replay",
{
"checked_after_check": True,
"checked_after_uncheck": False,
"note_value": "note-1",
"badge_text": "alice:editor",
},
{
"checked_after_check": checked_after_check,
"checked_after_uncheck": checked_after_uncheck,
"note_value": pg.get_by_placeholder("请输入备注").input_value(),
"badge_text": badge_text,
},
))
# Case 2: All 8 locator priority strategies uniquely resolve target elements
counts = {
"role": pg.get_by_role("button", name="提交").count(),
"text": pg.get_by_text("欢迎使用录制功能").count(),
"label": pg.get_by_label("用户名").count(),
"placeholder": pg.get_by_placeholder("请输入备注").count(),
"alt_text": pg.get_by_alt_text("产品图标").count(),
"test_id": pg.get_by_test_id("status-badge").count(),
"title": pg.get_by_title("状态提示").count(),
"css": pg.locator(".css-fallback").count(),
}
cases.append(make_case(
"locator_priority_resolution",
{k: 1 for k in counts},
counts,
))
# Case 3: Codegen assertion actions (Visibility, Text, Value, Snapshot)
expect(pg.get_by_test_id("status-badge")).to_be_visible()
expect(pg.get_by_test_id("status-badge")).to_have_text("alice:editor")
expect(pg.get_by_label("用户名")).to_have_value("alice")
snap_bytes = pg.get_by_test_id("status-badge").screenshot()
cases.append(make_case(
"assertion_types_verification",
{"assertions_passed": True, "snapshot_is_png": True},
{"assertions_passed": True, "snapshot_is_png": snap_bytes[:8] == b"\x89PNG\r\n\x1a\n"},
))
ctx.close()
# Case 4: Codegen CLI emulation & storage options (--viewport-size, --device, --color-scheme, --load-storage)
ctx_vp = browser.new_context(
base_url=base,
viewport={"width": 375, "height": 812},
color_scheme="dark",
storage_state=str(auth_file),
)
pg_vp = ctx_vp.new_page()
pg_vp.goto("/whoami")
vp_state = pg_vp.evaluate("() => ({w: window.innerWidth, h: window.innerHeight, dark: matchMedia('(prefers-color-scheme: dark)').matches})")
sess_val = pg_vp.locator("#sess").text_content()
ctx_vp.close()
iphone_vp = p.devices["iPhone 15"]["viewport"]
cases.append(make_case(
"codegen_emulation_and_storage_options",
{
"custom_viewport": [375, 812],
"dark_mode": True,
"restored_session": "saved42",
"iphone15_viewport": [393, 659],
},
{
"custom_viewport": [vp_state["w"], vp_state["h"]],
"dark_mode": vp_state["dark"],
"restored_session": sess_val,
"iphone15_viewport": [iphone_vp["width"], iphone_vp["height"]],
},
))
finally:
browser.close()
finally:
server.shutdown()
server.server_close()
print(json.dumps({"cases": cases}, ensure_ascii=False))
if __name__ == "__main__":
main()
- 核对导航/点击/填写/选择/勾选回放、8 级定位策略均唯一命中、可见/文本/值断言与 PNG 截图,以及视口/深色模式/状态加载参数生效。
所需环境:Windows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。
当前源码 SHA256:a6226e11df3157f2fcfb148493a76044ee2f35e1227ff77c55b2ec13596edcd9
本地运行
解压后按 README 说明在对应本地环境运行脚本。
所需环境:Windows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。
ZIP SHA256:9dfe2babc056275e2084d0f81036ef09128b85d2d10511d3827aaf52161c1e24
常见错误与边界
- 实际端口、文档资源与应用配置都应和测试条件一致。
练习与解答
为什么 Codegen 会把 getByRole() 和 getByLabel() 排在 CSS 选择器 locator() 之前?录制需要登录的后台页面时推荐搭配哪两个选项?
展开参考解答
基于 ARIA 角色与可见标签的定位更贴近用户实际交互方式,不因样式类名或 DOM 层级重构而脆弱失效;录制需登录页面可先用 --save-storage=auth.json 登录并落盘,再通过 --load-storage=auth.json 直接从已登录状态开始录制。