1、断点调试
在需要进行断点的地方可以使用page.pause()方法进行断点调试
同时会打开Playwright inspector,点开录制按钮,可以使用inspector进行操作录制,来定位元素
打开控制台,可以使用以下api进行元素定位,看定位是否对
- playwright.$(selector) 使用实际的Playwright查询引擎查询Playwright选择器
- playwright.$$(selector) 是返回全部的匹配元素
- playwright.inspect(selector) 在元素面板中显示元素(如果相应浏览器的DevTools支持)。
- playwright.locator(selector) 使用实际的Playwright查询引擎查询Playwright元素
- playwright.selector(element) 为给定元素生成选择器。
2、使用pytest执行playwright用例
安装插件 pip install pytest-playwright
运行时可以使用pytest 命令执行用例,规则同pytest命令
例如可以执行时查找以test开头的文件和方法
可以使用各种前置后置方法等
pytest test_my_application.py --headed 以有头模式运行用例
pytest test_login.py --browser webkit 以特定浏览器运行,默认chrome
3、拦截请求,修改请求
page.route拦截请求,第二个参数handle,拦截后回调方法
回调方法中,fulfill,可以将准备好的mock数据返回
注意:拦截方法一定要在请求发出之前,否则拦截不到
def handle(route):
print('0000000')
route.fulfill(json=json)
page.route("https://onion.xxx.com/servercase/plan/list?pageIndex=1&pageSize=20", handle)
page.goto("https://onion.xxx.com/#/serviceplan/testplan")
request,拦截到的请求实体
def intercept_request(route, request):
# 打印请求 URL
print(f"Intercepted request to {request.url}")
# 修改请求 URL
if request.url == "https://api.example.com/user":
new_url = "https://api.example.com/mock-user"
print(f"Redirecting to {new_url}")
route.continue_(url=new_url)
else:
# 修改请求头
headers = request.headers
headers["X-Custom-Header"] = "MyValue"
print(f"Modified headers: {headers}")
route.continue_(headers=headers)
def handle(route, request):
print('0000000')
response = route.fetch(method='POST', url=request.url, headers={
"Content-Type": "application/json",
"X-Custom-Header": "MyValue"
}, post_data=body)
json = response.json()
print(json)
json['data']['list'] = [
{
"planId": 6885,
"name": "手动下发确认",
"iworkIds": "xxzlzl-3344",
"process": 0,
"caseInfo": "0:0:0",
"bugInfo": "0:0:0",
"status": "未开始",
"owners": "888",
"bizName": "ssss"
}
]
print(json)
route.fulfill(response=response, json=json)
先发送请求,然后修改请求结果