playwright

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

Playwright

Playwright

Overview

概述

Playwright is a browser automation framework for Node.js and Python supporting Chromium, Firefox, and WebKit with a single API. It provides auto-waiting, web-first assertions, and full test isolation for reliable end-to-end testing.
When to use: Browser automation, web scraping, screenshot/PDF generation, API testing, configuring Playwright Test, troubleshooting Playwright errors, stealth mode and anti-bot bypass.
When NOT to use: Simple HTTP requests (use
fetch
), unit testing (use Vitest/Jest), serverless scraping at scale (consider Cloudflare Browser Rendering). For E2E test architecture (Page Object Models, CI sharding, test organization, authentication patterns), use the
e2e-testing
skill.
Playwright 是一款支持 Node.js 和 Python 的浏览器自动化框架,通过单一API即可操作 Chromium、Firefox 和 WebKit 浏览器。它提供自动等待、Web优先断言和完全测试隔离能力,可实现可靠的端到端测试。
适用场景: 浏览器自动化、网页抓取、截图/PDF生成、API测试、配置Playwright Test、排查Playwright错误、隐身模式与反机器人绕过。
不适用场景: 简单HTTP请求(请使用
fetch
)、单元测试(请使用Vitest/Jest)、大规模无服务器抓取(可考虑Cloudflare Browser Rendering)。若涉及端到端测试架构(页面对象模型、CI分片、测试组织、认证模式),请使用
e2e-testing
技能。

Quick Reference

快速参考

PatternAPI / ConfigKey Points
Basic test
test('name', async ({ page }) => {})
Auto-wait, web-first assertions, test isolation
Locator
page.getByRole()
/
page.locator()
Prefer role/label/text selectors over CSS
Assertion
expect(locator).toBeVisible()
Auto-retrying, configurable timeout
API testing
request
fixture /
apiRequestContext
Send HTTP requests, validate responses
Aria snapshot
expect(locator).toMatchAriaSnapshot()
Validate accessibility tree structure via YAML
Class assertion
expect(locator).toContainClass('active')
Match individual CSS class names (v1.52+)
Visible filter
locator.filter({ visible: true })
Match only visible elements (v1.51+)
Test step
test.step('name', async (step) => {})
Timeout, skip, and attachments (v1.50+)
Stealth mode
playwright-extra
+ stealth plugin
Patches 20+ detection vectors
Authenticated session
context.cookies()
+
addCookies()
Save/restore cookies and IndexedDB for persistence
Screenshot
page.screenshot({ fullPage: true })
Use
waitUntil: 'networkidle'
first
PDF generation
page.pdf({ format: 'A4' })
Chromium only, set
printBackground: true
Docker
mcr.microsoft.com/playwright:v1.58.0-noble
Use
--init --ipc=host
flags
Debug methods
page.consoleMessages()
/
page.requests()
(v1.56+)
No event listeners needed
SpeedboardHTML reporter (v1.57+)Identifies slow tests and bottlenecks
Playwright Agents
npx playwright init-agents
Planner, generator, healer for LLM-driven testing
Flaky test detection
--fail-on-flaky-tests
(v1.50+)
Exit code 1 on flaky tests in CI
模式API / 配置核心要点
基础测试
test('name', async ({ page }) => {})
自动等待、Web优先断言、测试隔离
定位器
page.getByRole()
/
page.locator()
优先使用角色/标签/文本选择器而非CSS
断言
expect(locator).toBeVisible()
自动重试、可配置超时时间
API测试
request
夹具 /
apiRequestContext
发送HTTP请求、验证响应内容
Aria快照
expect(locator).toMatchAriaSnapshot()
通过YAML验证无障碍树结构
类断言
expect(locator).toContainClass('active')
匹配单个CSS类名(v1.52+)
可见性筛选器
locator.filter({ visible: true })
仅匹配可见元素(v1.51+)
测试步骤
test.step('name', async (step) => {})
超时、跳过与附件功能(v1.50+)
隐身模式
playwright-extra
+ stealth plugin
修补20+种检测向量
认证会话
context.cookies()
+
addCookies()
保存/恢复Cookie与IndexedDB以实现持久化
截图
page.screenshot({ fullPage: true })
先使用
waitUntil: 'networkidle'
PDF生成
page.pdf({ format: 'A4' })
仅支持Chromium,需设置
printBackground: true
Docker部署
mcr.microsoft.com/playwright:v1.58.0-noble
使用
--init --ipc=host
参数
调试方法
page.consoleMessages()
/
page.requests()
(v1.56+)
无需事件监听器
SpeedboardHTML报告器(v1.57+)识别慢测试与性能瓶颈
Playwright Agents
npx playwright init-agents
基于LLM的测试规划、生成与修复工具
不稳定测试检测
--fail-on-flaky-tests
(v1.50+)
CI中出现不稳定测试时返回退出码1

Common Mistakes

常见错误

MistakeCorrect Pattern
Using CSS selectors over role selectorsPrefer
getByRole
,
getByLabel
,
getByText
for resilience
Not closing browserAlways
await browser.close()
in
finally
block
Using
setTimeout
for waits
Use
waitForSelector
,
waitForLoadState
, auto-wait
page.pause()
left in CI code
Guard with
if (!process.env.CI)
— hangs CI indefinitely
Clicking without waitingUse
locator().click()
with built-in auto-wait
Shared state between testsEach test gets fresh context via fixtures
Testing implementation detailsAssert user-visible behavior, not DOM structure
Hardcoded waits for dynamic contentWait for selector appearance or content stabilization
Missing
await
on assertions
All
expect()
assertions return promises — must be awaited
Same user agent for all scrapingRotate user agents for high-volume scraping
错误操作正确做法
使用CSS选择器而非角色选择器优先使用
getByRole
getByLabel
getByText
以提升鲁棒性
未关闭浏览器始终在
finally
块中执行
await browser.close()
使用
setTimeout
等待
使用
waitForSelector
waitForLoadState
或自动等待机制
CI代码中遗留
page.pause()
if (!process.env.CI)
做判断——否则会导致CI无限期挂起
未等待就点击使用
locator().click()
,其内置自动等待功能
测试间共享状态每个测试通过夹具获取全新上下文
测试实现细节断言用户可见行为,而非DOM结构
为动态内容设置硬编码等待时间等待选择器出现或内容稳定
断言时遗漏
await
所有
expect()
断言均返回Promise——必须使用await等待
所有抓取使用相同用户代理高容量抓取时轮换用户代理

Delegation

任务委托

  • Selector troubleshooting: Use
    Explore
    agent
  • Test pattern review: Use
    Task
    agent
  • Code review: Delegate to
    code-reviewer
    agent
For E2E test architecture, Page Object Model patterns, CI sharding strategies, authentication flows, visual regression workflows, or test organization, use the
e2e-testing
skill.
  • 选择器排查:使用
    Explore
    agent
  • 测试模式评审:使用
    Task
    agent
  • 代码评审:委托给
    code-reviewer
    agent
若涉及端到端测试架构、页面对象模型模式、CI分片策略、认证流程、视觉回归工作流或测试组织,请使用
e2e-testing
技能。

References

参考资料

  • Quick start and installation
  • E2E testing patterns and assertions
  • Selector strategies and best practices
  • Configuration and Docker deployment
  • Docker and CI
  • Debug methods and performance analysis
  • Common automation patterns
  • Stealth mode and anti-bot bypass
  • Known issues and solutions
  • Site-specific blocking and bypasses
  • Troubleshooting common problems
  • Advanced topics: MCP, AI agents, parallel contexts
  • 快速入门与安装
  • 端到端测试模式与断言
  • 选择器策略与最佳实践
  • 配置与Docker部署
  • Docker与CI
  • 调试方法与性能分析
  • 常见自动化模式
  • 隐身模式与反机器人绕过
  • 已知问题与解决方案
  • 站点特定拦截与绕过方案
  • 常见问题排查
  • 高级主题:MCP、AI Agent、并行上下文