Playwright 提供了一个名为 playwright-cli
的命令行工具,其中包含一个强大的功能:能够录制用户在浏览器中的操作并自动生成 Playwright 测试脚本。这极大地简化了测试脚本的编写过程,特别是对于不熟悉编程的测试同学来说。
安装好 Playwright 后,执行此命令,Playwright 将启动一个浏览器窗口,并开始记录你的操作。你在浏览器中执行的每一个动作(如点击、输入等)都会被转换成 Playwright 的 API 调用,并实时显示在另一个脚本生成的窗口中。
1. 开启脚本录制窗口命令:playwright codegen <URL>
# 控制台中执行以下脚本
playwright codegen https://playwright.dev/
# 查看帮助
playwright codegen --help
# playwright codegen 可以添加很多参数,可以根据实际需要进行选择
Usage: playwright codegen [options] [url]
open page and generate code for user actions
Options:
-o, --output <file name> saves the generated script to a file
--target <language> language to generate, one of javascript, playwright-test, python, python-async, python-pytest, csharp, csharp-mstest, csharp-nunit, java, java-junit (default: "python")
--save-trace <filename> record a trace for the session and save it to a file
--test-id-attribute <attributeName> use the specified attribute to generate data test ID selectors
-b, --browser <browserType> browser to use, one of cr, chromium, ff, firefox, wk, webkit (default: "chromium")
--block-service-workers block service workers
--channel <channel> Chromium distribution channel, "chrome", "chrome-beta", "msedge-dev", etc
--color-scheme <scheme> emulate preferred color scheme, "light" or "dark"
--device <deviceName> emulate device, for example "iPhone 11"
--geolocation <coordinates> specify geolocation coordinates, for example "37.819722,-122.478611"
--ignore-https-errors ignore https errors
--load-storage <filename> load context storage state from the file, previously saved with --save-storage
--lang <language> specify language / locale, for example "en-GB"
--proxy-server <proxy> specify proxy server, for example "http://myproxy:3128" or "socks5://myproxy:8080"
--proxy-bypass <bypass> comma-separated domains to bypass proxy, for example ".com,chromium.org,.domain.com"
--save-har <filename> save HAR file with all network activity at the end
--save-har-glob <glob pattern> filter entries in the HAR by matching url against this glob pattern
--save-storage <filename> save context storage state at the end, for later use with --load-storage
--timezone <time zone> time zone to emulate, for example "Europe/Rome"
--timeout <timeout> timeout for Playwright actions in milliseconds, no timeout by default
--user-agent <ua string> specify user agent string
--viewport-size <size> specify browser viewport size in pixels, for example "1280, 720"
-h, --help display help for command
2. 脚本录制界面如下