使用 Playwright 录制功能快速生成脚本
Playwright 的录制功能非常强大,可以实时记录你的操作并生成代码。下面是详细的使用指南:
1. 安装与基本使用
安装 Playwright Python 包
pip install playwright
安装浏览器驱动
playwright install chromium
playwright install firefox
playwright install webkit
启动录制工具
基础录制
playwright codegen
录制特定网站
playwright codegen https://example.com
指定浏览器(推荐 Chromium)
playwright codegen --browser=chromium https://example.com
保存录制文件
playwright codegen -o recorded_script.py https://example.com
设备模拟
playwright codegen --device="iPhone 12" https://example.com
2. 录制 iframe 操作技巧
录制准备
当页面包含 iframe 时,录制需要特殊处理:
- 设置超时时间:启动录制时设置较长的超时时间,给 iframe 加载留足时间。
playwright codegen --timeout=30000 https://your-target-site.com
录制过程操作指南
- 等待 iframe 加载:录制前手动等待几秒让 iframe 完全加载。
- 点击前验证:确保能看到 iframe 内容再操作。
- 层级切换:如果需要操作多层 iframe,逐层进入。
生成的代码示例
录制操作后,Playwright 会生成类似这样的代码:
from playwright.sync_api import sync_playwright, expect
def run(playwright):
browser = playwright.chromium.launch(headless=False)
context = browser.new_context(
viewport={"width": 1920, "height": 1080},
user_agent=
)
context.set_default_timeout()
page = context.new_page()
page.goto()
page.locator().fill()
page.locator().fill()
page.locator().click()
page.wait_for_url()
page.wait_for_selector()
frame = page.frame_locator()
frame.locator().click()
page.wait_for_timeout()
page.screenshot(path=)
context.close()
browser.close()
sync_playwright() playwright:
run(playwright)

