控制台与评估
🌐 Console & Eval
控制台消息
🌐 Console messages
playwright-cli console # all messages (info and above)
playwright-cli console error # errors only
playwright-cli console warning # warnings and errors
playwright-cli console debug # everything
playwright-cli console --clear # clear the message buffer
每个级别都包括更严重级别的消息;默认是 info。输出以计数行开始,这样你可以一眼看出页面是否干净:
🌐 Each level includes the messages of more severe levels; the default is info. The output starts
with a count line, so you can tell at a glance whether a page is clean:
$ playwright-cli console error
# Total messages: 37 (Errors: 2, Warnings: 5)
# Returning 2 messages for level "error"
#
# [ERROR] Uncaught TypeError: Cannot read property 'map' of undefined @ app.js:42
# [ERROR] Failed to load resource: 404 (Not Found) @ /api/users
工作流程:调试损坏的页面
🌐 Workflow: debugging a broken page
# Check the console for errors
playwright-cli console error
# [ERROR] Failed to fetch: GET https://api.example.com/data 404
# Now you know the API endpoint is returning 404
# Mock the route or investigate further
playwright-cli route "**/api/data" \
--body='{"items":[]}' --content-type=application/json
playwright-cli reload
JavaScript 评估
🌐 JavaScript evaluation
playwright-cli eval <func> [target]
这个参数是一个函数——页面用 () => { ... },当指定目标时用 element => { ... }。传入 --filename 可以将结果写入文件,而不是直接返回。
🌐 The argument is a function — () => { ... } for the page, element => { ... } when a target is
given. Pass --filename to write the result to a file instead of returning it inline.
页面级评估
🌐 Page-level evaluation
$ playwright-cli eval "() => document.title"
# React - TodoMVC
$ playwright-cli eval "() => window.innerWidth + 'x' + window.innerHeight"
# 1280x720
$ playwright-cli eval "() => JSON.stringify([...document.querySelectorAll('a')].map(a => a.href))" \
--filename=links.json
元素评估
🌐 Element evaluation
eval 是查看快照未显示属性的方法 — id、class、data-*,计算样式:
$ playwright-cli eval "el => el.id" e15
# item-42
$ playwright-cli eval "el => el.getAttribute('data-testid')" e15
# todo-item
$ playwright-cli eval "el => getComputedStyle(el).color" e5
# rgb(255, 0, 0)
管道结果
🌐 Piping results
--raw 会去掉页面状态和快照,只留下值:
playwright-cli --raw eval "JSON.stringify(performance.timing)" | jq '.loadEventEnd - .navigationStart'
运行 Playwright 代码
🌐 Running Playwright code
使用完整的 API 访问执行任意 Playwright 脚本:
🌐 Execute arbitrary Playwright scripts with full API access:
playwright-cli run-code <code>
playwright-cli run-code --filename=script.js
代码必须是一个单一的函数表达式——它被封装在 (...) 中并执行,所以 import / require 是不可用的。它会接收当前的 page,无论返回什么都会被打印出来。
🌐 The code must be a single function expression — it is wrapped in (...) and evaluated, so
import / require are not available. It receives the current page, and whatever it returns is
printed.
设置地理位置
🌐 Set geolocation
playwright-cli run-code "async (page) => {
await page.context().grantPermissions(['geolocation']);
await page.context().setGeolocation({latitude: 37.77, longitude: -122.42});
}"
等待特定条件
🌐 Wait for a specific condition
playwright-cli run-code "async (page) => {
await page.waitForSelector('.data-loaded');
return 'Data loaded successfully';
}"
模拟媒体
🌐 Emulate media
playwright-cli run-code "async (page) => page.emulateMedia({ colorScheme: 'dark' })"
在iframe里工作
🌐 Work inside an iframe
playwright-cli run-code "async (page) => {
const frame = page.locator('iframe#checkout').contentFrame();
await frame.getByRole('button', { name: 'Pay' }).click();
}"
抓取结构化数据
🌐 Scrape structured data
playwright-cli run-code "async (page) => {
const items = await page.$$eval('.product', els =>
els.map(el => ({
name: el.querySelector('.name').textContent,
price: el.querySelector('.price').textContent
}))
);
return JSON.stringify(items, null, 2);
}"