Playwright提供了一个Playwright Trace Viewer工具来追踪测试执行,这是一个GUI工具,我们可以通过它探索记录的 Playwright 测试跟踪,我们可以看到每个操作使用了哪个定位器,以及每个操作运行所需的时间,也可以在测试的每个操作中前后移动,并直观地查看每个操作期间发生的情况。
trace代码示例
from playwright.sync_api import sync_playwright
import time
with sync_playwright() as p:
browser = p.chromium.launch()
context = browser.new_context()
context.tracing.start(screenshots=True, snapshots=True) //trace开始
page = context.new_page()
page.goto("https://www.baidu.com/")
page.locator("#kw").fill("playwright")
page.get_by_role("button", name="百度一下").click()
context.tracing.stop(path="trace_demo2.zip") //trace结束,并保存trace结果
context.close()
browser.close()
查看trace
playwright show-trace C:\Users\Administrator\PycharmProjects\playwright\trace_demo2.zip
也可以通过访问 Playwright Trace Viewer 的方法,然后选择录制好的trace.zip文件即可打开
trace chunk
如果我们想在同一个BrowserContext上记录多个跟踪,可以使用
context.tracing.start_chunk() 和context.tracing.stop_chunk()。在这里就直接引用官方的demo了,代码如下:
context.tracing.start(screenshots=True, snapshots=True)
page = context.new_page()
page.goto("https://playwright.dev")
context.tracing.start_chunk()
page.get_by_text("Get Started").click()
# Everything between start_chunk and stop_chunk will be recorded in the trace.
context.tracing.stop_chunk(path = "trace1.zip")
context.tracing.start_chunk()
page.goto("http://example.com")
# Save a second trace file with different actions.
context.tracing.stop_chunk(path = "trace2.zip")
后续优化思路
我们可以在生成的 zip文件夹中的trace.trace文件里,搜索关键字"type":"action ,然后计算endTime 和startTime的差值,作一些后续的处理,比如统计action的具体执行时间,超出时间进行报警等等。
{"type":"action","metadata":{"id":"call@9","stack":[{"file":"C:/Users/Administrator/PycharmProjects/playwright/base_demo.py","line":44,"function":"<module>"}],"apiName":"Locator.click","objectId":"frame@61702569419795f9438e493e5d79c782","pageId":"page@e08915751c88d483c6eec247705ec11d","frameId":"frame@61702569419795f9438e493e5d79c782","wallTime":1706063443859,"startTime":2395079425.924,"endTime":2395079535.887,"type":"Frame","method":"click","params":{"selector":"internal:role=button[name=\"百度一下\"i]","strict":true},"log":["waiting for get_by_role(\"button\", name=\"百度一下\")"," locator resolved to <input id=\"su\" value=\"百度一下\" type=\"submit\" class=\"bg s_b…/>","attempting click action"," waiting for element to be visible, enabled and stable"," element is visible, enabled and stable"," scrolling into view if needed"," done scrolling"," performing click action"," click action done"," waiting for scheduled navigations to finish"," navigations have finished"],"snapshots":[{"title":"before","snapshotName":"before@call@9"},{"title":"action","snapshotName":"action@call@9"},{"title":"after","snapshotName":"after@call@9"}],"afterSnapshot":"after@call@9","point":{"x":781,"y":35}}}
我的每一篇文章都希望帮助读者解决实际工作中遇到的问题!如果文章帮到了您,劳烦点赞、收藏、转发!您的鼓励是我不断更新文章最大的动力!