启动playwright录制codegen生成自动化测试脚本

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批量执行

相关推荐
虎头金猫2 小时前
4K 视频总卡在公网带宽?用 N1 + OpenList 把网盘播放链路重新理顺
运维·服务器·网络·python·容器·beautifulsoup·pandas
长沙三为智能科技2 小时前
家政小程序开发从0到上线:五阶段交付流程与验收清单
python
伞伞悦读3 小时前
【第38期】Python 模块与包详解:import、from、模块搜索路径、包结构和 __init__
开发语言·python
只睡四小时3 小时前
Canvas 弹道联机实战:700 行 + 固定时间步长
python·websocket·html5·游戏开发·canvas
奇思妙想聪明勤奋的小羊4 小时前
DeepAgents第5章:子Agent 与上下文隔离—让 Agent学会委派
人工智能·python·学习·语言模型
lpfasd1234 小时前
2026年第38周GitHub趋势周报
python·科技·github
IZero074 小时前
Jev 与 Laya
python·语言模型
2601_962218615 小时前
万象生鲜系统称重自动多退少补算法解决生鲜非标品痛点
大数据·数据库·人工智能·python·算法