官网

官方:
https://playwright.dev/docs/intro
中文网:
https://playwright.nodejs.cn/

高频常用语法

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
// 启动并打开页面
with sync_playwright() as p:
browser = p.chromium.launch(headless=False) # 改成 True 可后台
context = browser.new_context()
page = context.new_page()

// 输入 & 点击
page.locator('#user').fill('admin');
page.getByRole('button', { name: '登录' }).click();

// 断言
expect(page.locator('.welcome')).toHaveText('欢迎 admin');

// 截图
page.screenshot({ path: 'login.png', fullPage: true });

// 关闭
browser.close();

异步版本

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
// 启动并打开页面
import asyncio
from playwright.async_api import async_playwright

async def main():
async with async_playwright() as p:
browser = await p.chromium.launch(headless=False, slow_mo=100)
page = await browser.new_page()
await page.goto("https://example.com")
await page.locator("h1").click()

await asyncio.Event().wait() # 永久挂起
await browser.close()

if __name__ == "__main__":
asyncio.run(main())

// 输入 & 点击
await page.locator('#user').fill('admin');
await page.getByRole('button', { name: '登录' }).click();

// 断言
await expect(page.locator('.welcome')).toHaveText('欢迎 admin');

// 截图
await page.screenshot({ path: 'login.png', fullPage: true });

// 关闭
await browser.close();

远程连接浏览器

开放浏览器端口

1
start chrome --remote-debugging-address=0.0.0.0 --remote-debugging-port=9222 --user-data-dir="D:\下载\tmp" --no-first-run --no-default-browser-check --incognito

连接

1
2
3
4
5
6
7
8
from playwright.sync_api import sync_playwright

with sync_playwright() as p:
browser = p.chromium.connect_over_cdp("http://localhost:9222")
context = browser.contexts[0]
page = context.pages[0]
page.goto("https://www.baidu.com")
print(page.title())

录制生成代码

  1. 常用:
1
playwright codegen https://example.com -b chromium --target python -o mobile_test.py
  1. 直接启动录制:
1
playwright codegen https://example.com

或者无网址

参数

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
# Playwright codegen 参数速查表
# 运行:npx playwright codegen [URL] [OPTIONS]

# 基本
-o, --output <file> 保存录制脚本到文件
-b, --browser <name> 指定浏览器:chromium|firefox|webkit
--channel <channel> 指定浏览器渠道:chrome|msedge|chrome-beta 等
--target <language> 输出语言:python|python-async|javascript|java|csharp|test

# 设备与视口
--device <deviceName> 模拟设备,如 "iPhone 11"
--viewport-size <w,h> 自定义窗口大小,如 1280,720

# 环境
--lang <lang> 页面语言,如 zh-CN
--color-scheme <scheme> 颜色模式:light|dark|no-preference
--timezone <tz> 时区,如 Asia/Shanghai
--geolocation <lat,lng> 经纬度,如 31.2,121.5

# 登录态
--save-storage <file> 录制完成后保存浏览器状态(cookies/localStorage)
--load-storage <file> 启动时加载浏览器状态

# 网络与代理
--proxy-server <url> HTTP/HTTPS/SOCKS 代理,如 http://127.0.0.1:8888
--user-agent <ua> 自定义 UA 字符串

# 其他
--timeout <ms> 默认动作超时,毫秒
--ignore-https-errors 忽略 HTTPS 证书错误
--headless 无头模式运行(默认录制时为 headed)

基础语法速查表

Playwright 基础语法速查表(极简版)

分类 方法 简要说明
浏览器 chromium.launch() 启动浏览器
browser.newContext() 创建隔离上下文
context.newPage() 新建页面
元素定位 locator() CSS/XPath/文本通用定位
getByRole() 按 ARIA 角色定位
getByText() 按文本内容定位
getByTestId() data-testid 属性定位
输入 .fill() 清空后输入文本
.type() 逐字符输入
点击 .click() 左键单击
.dblclick() 双击
选择 .check() 勾选复选框/单选
.uncheck() 取消勾选
下拉 .selectOption() 选择下拉选项
键盘 .press() 发送单个按键
鼠标 .hover() 悬停
文件上传 .setInputFiles() 设置文件输入框
截图 .screenshot() 页面/元素截图
PDF .pdf() 导出 PDF
断言 .toBeVisible() 元素可见
.toHaveText() 包含文本
网络 page.route() 拦截/修改请求
等待 page.waitForURL() 等待导航完成
locator.waitFor() 等待元素出现