1、先装好 Playwright
npx playwright codegen shturl.cc/eSLas
(npx playwright codegen --target python -o tests/test_record.py https://XXX.com/
一、前置安装(只需要执行一次)打开 cmd/powershell(Windows)或者终端bash# 1.初始化项目(新建文件夹,cd进去)
npm init -y
2.安装playwright
npm install playwright
3.自动下载浏览器内核(非常重要,不执行打不开浏览器)
npx playwright install
如果你想用Python 版本,命令不一样:
bashpip install playwright
playwright install
python版codegen启动命令
playwright codegen shturl.cc/eSLas
二、执行录制命令bashnpx playwright codegen shturl.cc/eSLas
运行之后,会同时弹出 2 个窗口
浏览器窗口:就是你要操作的被测网站,你点页面、输入文字,全部自动录下来
Playwright Inspector(检查器):实时生成代码,左边是操作记录,右边是生成脚本
常用参数(你做多语言海外站点很实用)bash# 直接生成Python脚本,保存到test.py
npx playwright codegen --target=python -o test.py shturl.cc/eSLas
指定浏览器(firefox / webkit / chromium)
npx playwright codegen --browser=firefox shturl.cc/eSLas
登录后保存cookie,下次录制免登录
npx playwright codegen --save-storage=auth.json shturl.cc/eSLas
下次打开直接带登录态
npx playwright codegen --load-storage=auth.json shturl.cc/eSLas
三、录制操作步骤
在弹出的浏览器里正常操作:跳转页面、点击按钮、输入内容
在 Inspector 工具栏,可以加断言(重点!录制的时候直接加校验)
assert visibility:断言元素可见
assert text:断言文本内容
录制完成 → 点Copy复制代码,或者直接保存文件
关闭浏览器窗口,录制结束
四、重点提醒(踩坑点)
codegen 生成的是原始脚本,录制出来的 locator 有时候不够稳定,需要你后续人工优化,或者丢给 AI(TRAE/Continue)改成 POM 分层、增加异常截图、超时处理
推荐优先用role/text 定位,不要默认 xpath(多语种站点 xpath 容易失效)
VS Code 里装 Playwright 插件,也可以直接点Record new一键录制,不用敲命令
五、两种录制方式对比
命令行 codegen:适合快速录制、多浏览器切换、带登录态录制
VS Code 插件录制:录制代码直接写入项目文件,适合项目内写用例
六、录制后的工作流(适合你的多站点自动化)codegen录制原始脚本 → AI优化脚本 → 封装POM对象模型 → 增加失败截图、等待、异常处理 → pytest批量执行