| name | playwright-cli |
| description | 官方Microsoft Playwright CLI网页自动化工具,支持所有主流浏览器的无头/有头自动化操作,包括页面导航、元素交互、截图、录制、测试等功能。当用户提到网页自动化、浏览器操作、爬虫、截图、录制用户操作、E2E测试时触发。 |
Playwright CLI 技能
Playwright CLI是微软官方的浏览器自动化工具,支持Chromium、Firefox、WebKit三大主流浏览器,提供强大的网页自动化能力。
安装步骤
1. 安装Playwright CLI
npm install -g @playwright/test
pip install playwright
2. 安装浏览器
playwright install
playwright install chromium firefox
playwright install-deps
核心常用命令
页面操作
playwright open https://example.com
playwright screenshot https://example.com example.png
playwright screenshot https://example.com --full-page full.png
playwright screenshot https://example.com --viewport-size=1920,1080 desktop.png
playwright pdf https://example.com example.pdf
playwright pdf https://example.com --format=A4 --landscape report.pdf
录制用户操作
playwright codegen https://example.com
playwright codegen https://example.com --output script.py
playwright codegen https://example.com --target python
测试相关
playwright test
playwright test tests/example.spec.js
playwright test --headed
playwright test --debug
playwright show-report
浏览器管理
playwright list-browsers
playwright install --force
playwright uninstall chromium
使用示例
示例1:批量截图多个网页
for url in "https://google.com" "https://github.com" "https://stackoverflow.com"; do
name=$(echo $url | sed 's/https\?:\/\///' | sed 's/\//_/g')
playwright screenshot $url --full-page "${name}.png"
done
示例2:自动填写表单
from playwright.sync_api import Playwright, sync_playwright, expect
def run(playwright: Playwright) -> None:
browser = playwright.chromium.launch(headless=False)
context = browser.new_context()
page = context.new_page()
page.goto("https://example.com/login")
page.get_by_label("用户名").fill("your_username")
page.get_by_label("密码").fill("your_password")
page.get_by_role("button", name="登录").click()
page.screenshot(path="logged_in.png")
context.close()
browser.close()
with sync_playwright() as playwright:
run(playwright)
示例3:模拟移动端访问
playwright screenshot https://example.com --device="iPhone 14" mobile.png
playwright screenshot https://example.com --device="Galaxy S23" android.png
最佳实践
- 优先使用无头模式执行自动化任务,性能更高
- 复杂操作优先使用
codegen录制生成代码,再手动调整
- 执行长时间任务时添加
--slowmo=1000参数减慢操作速度,避免被反爬
- 保存登录状态使用
--save-storage=auth.json,下次可以直接--load-storage=auth.json跳过登录
- 网络不稳定时添加
--timeout=60000延长超时时间