Playwright 常用命令、参数详解及使用示例
Playwright 常用命令、参数详解及使用示例
一、基础安装与初始化
安装CLI工具
npm install -g @playwright/cli
playwright install # 安装浏览器驱动
生成测试代码
通过录制操作生成脚本:
npx playwright codegen https://example.com -o test.py --target python
-o
:输出文件路径--target
:生成语言(如python、javascript)-b
:指定浏览器(chromium/firefox/webkit)
二、核心参数详解
浏览器控制
--browser
:指定浏览器类型(默认chromium)--headed
:显示浏览器界面(默认无头模式)--device
:模拟移动设备(如"iPhone 11")
npx playwright test --browser=firefox --headed --device="Pixel 5"
调试与性能
--slowmo
:操作延迟(毫秒)--timeout
:全局超时时间(默认30秒)--viewport-size
:设置窗口大小(如1280,720)
npx playwright test --slowmo=2000 --timeout=60000
输出与记录
--screenshot
:截图模式(on/off/only-on-failure)--video
:录屏模式(同上)--output
:结果保存目录
npx playwright test --screenshot=on --video=retain-on-failure
三、配置文件示例
在playwright.config.ts
中定义默认参数:
import { defineConfig } from '@playwright/test';
export default defineConfig({timeout: 60000,use: {headless: false,viewport: { width: 1280, height: 720 },video: 'retain-on-failure'}
});
支持通过--config
指定配置文件。
四、Python示例代码
from playwright.sync_api import sync_playwrightwith sync_playwright() as p:browser = p.chromium.launch(headless=False, slow_mo=1000)page = browser.new_page(viewport={"width": 1600, "height": 900})page.goto("https://example.com")page.screenshot(path="example.png", full_page=True)browser.close()
此代码启动可视化浏览器,设置视口大小并截图。
五、高级场景
设备模拟
npx playwright open --device="iPhone 13" https://example.com
模拟移动端浏览,自动适配UA和分辨率。
认证状态复用
npx playwright codegen --save-storage=auth.json # 保存登录状态
npx playwright open --load-storage=auth.json # 加载状态
完整参数列表可通过npx playwright --help
查看最新文档。