5分钟极速上手Playwright脚本录制零代码实现Web自动化测试当产品经理突然丢给你一个刚上线的电商活动页要求半小时内完成所有核心链路测试时传统的手写Selenium脚本显然来不及。作为测试工程师我最近发现微软开源的Playwright有个作弊神器——codegen脚本录制功能能让没有任何编程基础的产品运营也能快速生成可执行的自动化测试脚本。上周我就用这个功能在客户演示前15分钟紧急补全了支付流程的冒烟测试成功避免了线上事故。1. 为什么选择Playwright录制而非手写代码去年我们团队评估过市面主流测试工具Playwright的录制功能在三个维度表现突出执行效率对比Chromium浏览器指标SeleniumCypressPlaywright脚本生成速度2分钟1分钟30秒代码可读性★★☆☆☆★★★☆☆★★★★☆跨语言支持4种1种5种实际体验中Playwright的录制器能智能识别多种交互场景文件上传对话框的自动处理动态加载元素的等待策略鼠标悬停等复杂事件捕获提示录制生成的代码默认包含智能等待机制比手动添加wait更可靠2. 零基础搭建录制环境只需要完成这两个前置步骤安装Node.js建议LTS版本# Mac/Linux用户推荐使用nvm curl -o- https://raw.githubusercontent.com/nvm-sh/nvm/v0.39.3/install.sh | bash nvm install --lts初始化Playwright环境npm init playwrightlatest安装过程会提示选择语言支持TypeScript默认JavaScriptPythonJavaC#遇到网络问题可尝试设置国内镜像npm config set registry https://registry.npmmirror.com3. 录制第一个测试脚本假设要测试百度搜索功能只需执行npx playwright codegen https://www.baidu.com这时会出现两个窗口浏览器窗口实际操作的Chrome实例代码窗口实时生成的测试脚本典型操作流程在搜索框输入Playwright点击百度一下按钮在结果页点击第一条链接按Stop按钮结束录制生成的Python示例代码from playwright.sync_api import Playwright, sync_playwright def run(playwright: Playwright) - None: browser playwright.chromium.launch(headlessFalse) context browser.new_context() page context.new_page() page.goto(https://www.baidu.com/) page.locator(#kw).fill(Playwright) page.locator(#su).click() page.locator(textPlaywright: Fast and reliable end-to-end testing).click() with sync_playwright() as playwright: run(playwright)4. 高级录制技巧与优化4.1 多语言切换在录制界面右上角可以实时切换输出语言比如从Python改为Javaimport com.microsoft.playwright.*; public class Example { public static void main(String[] args) { try (Playwright playwright Playwright.create()) { Browser browser playwright.chromium().launch(); Page page browser.newPage(); page.navigate(https://www.baidu.com/); page.locator(#kw).fill(Playwright); page.locator(#su).click(); page.locator(textPlaywright: Fast and reliable end-to-end testing).click(); } } }4.2 断言自动生成在操作过程中点击Record assertions按钮可以自动添加验证点# 断言搜索结果标题包含关键字 expect(page).to_have_title(re.compile(Playwright)) # 验证结果数量大于5条 expect(page.locator(#content_left h3)).to_have_count(greater_than(5))4.3 设备模拟启动时添加--device参数模拟移动端npx playwright codegen --deviceiPhone 13 https://m.baidu.com5. 从录制到生产的进阶路径虽然录制能快速产出脚本但要做好持续集成还需要元素定位优化将page.locator(#kw)改为search_input page.get_by_role(textbox, name搜索框)使用>pytest.fixture(scopemodule) def browser(): with sync_playwright() as p: browser p.chromium.launch() yield browser browser.close()集成到CI流水线# GitHub Actions示例 - name: Run Playwright tests run: | npx playwright install npx playwright test最近我在金融项目中将录制的脚本改造后测试用例执行时间从原来的18分钟降到了4分钟。关键是把重复操作抽象成POM模式再用录制功能快速生成新场景的测试骨架。