https://blog.csdn.net/liwenxiang629/article/details/130682736这篇文章系统地介绍了上手Playwright的方法,但是录制脚本部分讲解不够详尽,今天我在这里重点的介绍一下Playwright 录制脚本的方法来丰满我的Playwright系列技术文章。
Playwright可以使用codegen来录制脚本,使用方式非常简单,只要大家玩过ui自动化测试的录制相关工具五分钟就可以学会上手!
playwright Inspector录制脚本并生成不同的脚本语言
playwright Inspector进行页面录制非常简单,使用如下命令即可
playwright codegen https://www.baidu.com/
会启动chromium的浏览器页面,我们鼠标触碰的地方会被标记为红色,并显示其元素属性,如下图所示:
操作的过程会通过playwright Inspector记录,如下图所示:
我们还可以通过Target来选择把录制的脚本转化为项目需要的编程语言,这就是自动化测试中的录制工具,相信做过自动化测试的同学都会懂
录制过程直接生成py脚本
使用下面的命令会把我们在浏览器中的操作脚本化并保存到baidu_test.py中,
playwright codegen --target python -o baidu_test.py -b chromium https://www.baidu.com/
录制实例代码分析
from playwright.sync_api import Playwright, sync_playwright, expect
def run(playwright: Playwright) -> None:
browser = playwright.chromium.launch(headless=False)
context = browser.new_context()
page = context.new_page()
page.goto("https://www.baidu.com/")
page.locator("#kw").click()
page.locator("#kw").fill("test")
page.get_by_role("button", name="百度一下").click()
page.close()
context.close()
browser.close()
with sync_playwright() as playwright:
run(playwright)
相信有过自动化测试基础的同学都很容易理解关于page.goto()、page.locator("#kw").click(),page.locator("#kw").fill("test") 这些api的定义,就是最基础的操作:访问网页,点击元素,和输入数据,
上面的脚步中有两处python 语法需要说明一下
(playwright: Playwright) -> None
该用法叫做函数注释 Function Annotations,大家可以参考文章:
https://blog.csdn.net/liwenxiang629/article/details/112466737
with sync_playwright() as playwright:
with …as用于异常处理,可以使代码更简洁、可读性更强,大家可以参考文章
https://blog.csdn.net/liwenxiang629/article/details/130620609