playwright

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

Playwright Web Automation

Playwright 网页自动化

Browser automation via Chromium + playwright-core over CDP. No MCP server needed — scripts run as
.mjs
files.
通过Chromium + playwright-core基于CDP实现浏览器自动化。无需MCP服务器——脚本以
.mjs
文件形式运行。

Prerequisites

前置条件

bash
undefined
bash
undefined

Install playwright-core (no browser download — uses existing Chromium)

安装playwright-core(无需下载浏览器——使用已有的Chromium)

npm install playwright-core
npm install playwright-core

Verify Chromium exists

验证Chromium是否存在

which chromium || ls /Applications/Chromium.app/Contents/MacOS/Chromium
undefined
which chromium || ls /Applications/Chromium.app/Contents/MacOS/Chromium
undefined

Launch Chromium with CDP

通过CDP启动Chromium

bash
undefined
bash
undefined

Kill any existing debug instance

终止所有已存在的调试实例

pkill -f "remote-debugging-port=9222" 2>/dev/null
pkill -f "remote-debugging-port=9222" 2>/dev/null

Launch headless (cron/CI) or headed (interactive)

启动无头模式(用于cron/CI)或有头模式(交互式)

chromium --remote-debugging-port=9222
--user-data-dir="/tmp/playwright-profile"
--disable-blink-features=AutomationControlled
--no-first-run --no-default-browser-check
--headless=new
"about:blank" > /tmp/chromium.log 2>&1 &
chromium --remote-debugging-port=9222
--user-data-dir="/tmp/playwright-profile"
--disable-blink-features=AutomationControlled
--no-first-run --no-default-browser-check
--headless=new
"about:blank" > /tmp/chromium.log 2>&1 &

macOS: use full path /Applications/Chromium.app/Contents/MacOS/Chromium

macOS:使用完整路径 /Applications/Chromium.app/Contents/MacOS/Chromium

Linux: chromium-browser or chromium

Linux:使用chromium-browser或chromium

Wait for CDP

等待CDP就绪

sleep 3 && curl -sf http://localhost:9222/json/version > /dev/null && echo "CDP ready"
undefined
sleep 3 && curl -sf http://localhost:9222/json/version > /dev/null && echo "CDP ready"
undefined

Connect via Playwright (ESM)

通过Playwright(ESM)连接

Write scripts as
.mjs
files:
javascript
// run: node script.mjs
import { chromium } from 'playwright-core';

const browser = await chromium.connectOverCDP('http://localhost:9222');
const ctx = browser.contexts()[0];
const page = ctx.pages()[0] || await ctx.newPage();

await page.goto('https://example.com', { waitUntil: 'domcontentloaded', timeout: 15000 });
await page.waitForTimeout(2000);
await page.screenshot({ path: '/tmp/screenshot.png' });

await browser.close(); // disconnects, doesn't kill Chromium
IMPORTANT: Always use
.mjs
extension — playwright-core is ESM-only.
将脚本编写为
.mjs
文件:
javascript
// 运行:node script.mjs
import { chromium } from 'playwright-core';

const browser = await chromium.connectOverCDP('http://localhost:9222');
const ctx = browser.contexts()[0];
const page = ctx.pages()[0] || await ctx.newPage();

await page.goto('https://example.com', { waitUntil: 'domcontentloaded', timeout: 15000 });
await page.waitForTimeout(2000);
await page.screenshot({ path: '/tmp/screenshot.png' });

await browser.close(); // 断开连接,不会终止Chromium
重要提示: 务必使用
.mjs
扩展名——playwright-core仅支持ESM。

Key Patterns

核心模式

Screenshot & Inspect

截图与检查

javascript
await page.screenshot({ path: '/tmp/screen.png' });
// Read /tmp/screen.png in Claude to see it visually
javascript
await page.screenshot({ path: '/tmp/screen.png' });
// 在Claude中读取/tmp/screen.png以查看可视化内容

Fill Forms & Click

填写表单与点击

javascript
// Inspect inputs first
const inputs = await page.evaluate(() =>
  Array.from(document.querySelectorAll('input')).map(i => ({
    name: i.name, type: i.type, placeholder: i.placeholder
  }))
);
console.log(JSON.stringify(inputs, null, 2));

await page.fill('input[name="email"]', 'user@example.com');
await page.click('button:has-text("Submit")');
await page.waitForTimeout(2000);
javascript
// 先检查输入框
const inputs = await page.evaluate(() =>
  Array.from(document.querySelectorAll('input')).map(i => ({
    name: i.name, type: i.type, placeholder: i.placeholder
  }))
);
console.log(JSON.stringify(inputs, null, 2));

await page.fill('input[name="email"]', 'user@example.com');
await page.click('button:has-text("Submit")');
await page.waitForTimeout(2000);

Extract Page Content

提取页面内容

javascript
const text = await page.evaluate(() => document.body.innerText);
const html = await page.content();
const title = await page.title();
javascript
const text = await page.evaluate(() => document.body.innerText);
const html = await page.content();
const title = await page.title();

Wait for Navigation

等待导航完成

javascript
await Promise.all([
  page.waitForNavigation({ waitUntil: 'networkidle' }),
  page.click('button:has-text("Login")')
]);
javascript
await Promise.all([
  page.waitForNavigation({ waitUntil: 'networkidle' }),
  page.click('button:has-text("Login")')
]);

SPA / Client-Side Rendered Data

SPA/客户端渲染数据

SPAs may not hydrate fully in headless. Use data endpoints if available:
javascript
const data = await page.evaluate(async () => {
  const res = await fetch('/api/data', { credentials: 'include' });
  return res.json();
});
无头模式下SPA可能无法完全加载。如果有可用的数据端点,请使用:
javascript
const data = await page.evaluate(async () => {
  const res = await fetch('/api/data', { credentials: 'include' });
  return res.json();
});

Multi-Page Flow

多页面流程

javascript
await page.goto('https://app.example.com/login');
await page.fill('#email', 'user@example.com');
await page.fill('#password', 'password');
await page.click('button[type="submit"]');
await page.waitForNavigation({ waitUntil: 'networkidle' });
await page.screenshot({ path: '/tmp/after-login.png' });

// Continue to next page
await page.click('a:has-text("Dashboard")');
await page.waitForLoadState('networkidle');
await page.screenshot({ path: '/tmp/dashboard.png' });
javascript
await page.goto('https://app.example.com/login');
await page.fill('#email', 'user@example.com');
await page.fill('#password', 'password');
await page.click('button[type="submit"]');
await page.waitForNavigation({ waitUntil: 'networkidle' });
await page.screenshot({ path: '/tmp/after-login.png' });

// 继续跳转到下一页
await page.click('a:has-text("Dashboard")');
await page.waitForLoadState('networkidle');
await page.screenshot({ path: '/tmp/dashboard.png' });

Record Video

录制视频

javascript
// Must create a NEW context for video recording
const ctx = await browser.newContext({
  recordVideo: { dir: '/tmp/videos/', size: { width: 1280, height: 720 } }
});
const page = await ctx.newPage();
await page.goto('https://example.com');
// ... do things ...
await ctx.close(); // video saved to /tmp/videos/*.webm
javascript
// 必须创建新的上下文以录制视频
const ctx = await browser.newContext({
  recordVideo: { dir: '/tmp/videos/', size: { width: 1280, height: 720 } }
});
const page = await ctx.newPage();
await page.goto('https://example.com');
// ... 执行操作 ...
await ctx.close(); // 视频将保存到/tmp/videos/*.webm

Console & Network Monitoring

控制台与网络监控

javascript
page.on('console', msg => console.log(`[${msg.type()}] ${msg.text()}`));
page.on('response', res => {
  if (res.status() >= 400) console.log(`[${res.status()}] ${res.url()}`);
});
javascript
page.on('console', msg => console.log(`[${msg.type()}] ${msg.text()}`));
page.on('response', res => {
  if (res.status() >= 400) console.log(`[${res.status()}] ${res.url()}`);
});

Selectors (prefer in this order)

选择器(优先顺序如下)

  1. data-testid="foo"
    page.click('[data-testid="foo"]')
  2. Role —
    page.getByRole('button', { name: 'Submit' })
  3. Text —
    page.click('button:has-text("Submit")')
  4. CSS —
    page.click('.submit-btn')
    (fragile, last resort)
  1. data-testid="foo"
    ——
    page.click('[data-testid="foo"]')
  2. 角色 ——
    page.getByRole('button', { name: 'Submit' })
  3. 文本 ——
    page.click('button:has-text("Submit")')
  4. CSS ——
    page.click('.submit-btn')
    (易失效,最后选择)

Cleanup

清理

bash
pkill -f "remote-debugging-port=9222"
bash
pkill -f "remote-debugging-port=9222"

Troubleshooting

故障排除

ProblemSolution
CDP not respondingWait longer, check
curl http://localhost:9222/json/version
Port 9222 in use
pkill -f "remote-debugging-port=9222"
then relaunch
ESM import errorUse
.mjs
extension, not
.js
Page not loadingIncrease timeout, use
waitUntil: 'domcontentloaded'
Screenshots blankAdd
page.waitForTimeout(2000)
before capture
CSS not loadedUse
waitUntil: 'networkidle'
or wait for a visible element
Form submit failsCheck if element is visible:
await el.isVisible()
问题解决方案
CDP无响应等待更长时间,检查
curl http://localhost:9222/json/version
端口9222被占用执行
pkill -f "remote-debugging-port=9222"
后重新启动
ESM导入错误使用
.mjs
扩展名,而非
.js
页面无法加载增加超时时间,使用
waitUntil: 'domcontentloaded'
截图空白在捕获前添加
page.waitForTimeout(2000)
CSS未加载使用
waitUntil: 'networkidle'
或等待可见元素
表单提交失败检查元素是否可见:
await el.isVisible()