快照
🌐 Snapshots
在每个命令之后,playwright-cli 会输出当前浏览器状态的快照——带有用于交互的元素引用的无障碍树。
🌐 After each command, playwright-cli outputs a snapshot of the current browser state — an accessibility tree with element refs for interaction.
自动快照
🌐 Automatic snapshots
每个命令都会返回页面信息和快照文件的链接:
🌐 Every command returns page info and a link to the snapshot file:
### Page
- Page URL: https://demo.playwright.dev/todomvc/#/
- Page Title: React - TodoMVC
### Snapshot
[Snapshot](.playwright-cli/page-2026-02-14T19-22-42-679Z.yml)
快照文件包含可访问性树:
🌐 The snapshot file contains the accessibility tree:
- heading "todos" [level=1]
- textbox "What needs to be done?" [ref=e5]
- listitem:
- checkbox "Toggle Todo" [ref=e10]
- text: "Buy groceries"
- listitem:
- checkbox "Toggle Todo" [ref=e14]
- text: "Water flowers"
- contentinfo:
- text: "2 items left"
- link "All" [ref=e20]
- link "Active" [ref=e21]
- link "Completed" [ref=e22]
元素引用
🌐 Element refs
每个交互元素都会获得一个唯一的引用(例如,e5、e10)。引用在单个快照中是稳定的,但在页面更改时会失效——导航后始终重新快照。
🌐 Each interactive element gets a unique ref (e.g., e5, e10). Refs are stable within a single snapshot but invalidated when the page changes — always re-snapshot after navigation.
| 属性 | 详情 |
|---|---|
| 格式 | e 后跟一个数字(例如,e1、e15、e203) |
| 范围 | 在单个快照中唯一 |
| 生命周期 | 有效直到下一次页面更改 |
| 分配 | 只有交互元素才会获得引用(按钮、链接、输入框等) |
按需快照
🌐 On-demand snapshots
playwright-cli snapshot # full page, timestamped filename
playwright-cli snapshot --filename=after.yaml # custom filename
playwright-cli snapshot "#main" # scope to CSS selector
playwright-cli snapshot e34 # scope to element ref
playwright-cli snapshot --depth=4 # limit tree depth
使用 refs
🌐 Using refs
playwright-cli click e10 # check the checkbox
playwright-cli fill e5 "Walk the dog" # type into textbox
playwright-cli hover e20 # hover over "All" link
使用选择器
🌐 Using selectors
CSS 选择器和 Playwright 定位器可以作为 refs 的替代方案:
🌐 CSS selectors and Playwright locators work as alternatives to refs:
# CSS selectors
playwright-cli click "#main > button.submit"
playwright-cli click "[data-testid='submit']"
# Playwright locators
playwright-cli click "getByRole('button', { name: 'Submit' })"
playwright-cli click "getByTestId('submit-button')"
playwright-cli click "getByText('Login')"
原始输出
🌐 Raw output
使用 --raw 去除页面信息,仅返回命令输出:
🌐 Use --raw to strip page info and return only command output:
playwright-cli snapshot --raw | grep "button"
最佳实践
🌐 Best practices
- 使用 refs,而不是选择器 — 来自快照的 refs 比 CSS 选择器更可靠,因为它们指向代理刚刚看到的确切元素
- 导航后重新快照 — 当页面变化时,引用会失效
- 限制深度 — 在复杂页面上使用
--depth以减少输出大小 - 限定到元素 — 截取页面的特定部分而不是整个页面
- 命名快照文件 — 当快照是工作流结果的一部分时使用
--filename - 检查对话框 — 如果命令报告有对话框打开,请在执行其他操作之前处理它