前言
page.expect_request() 可以捕获网页上发出去的请求,当有多个请求时,可以根据请求url,请求方式判断。
expect_request
官方文档示例
with page.expect_request("http://example.com/resource") as first:
page.get_by_text("trigger request").click()
first_request = first.value
# or with a lambda
with page.expect_request(lambda request: request.url == "http://example.com" and request.method == "get") as second:
page.get_by_text("trigger request").click()
second_request = second.value
expect_request 参数说明:
url_or_predicate : typing.Union[str, typing.Pattern[str], typing.Callable[["Request"], bool]]
请求URL字符串、正则表达式或接收Request参数的函数对象, 当通过上下文选项提供base_url并且传递的url是路径时,它将通过新的url()构造函数进行合并。
timeout: typing.Optional[float] = None
设置超时时间,默认30秒,单位毫秒, 传递0以禁用超时。可以使用page.set_default_timeout()方法更改默认值。
使用示例
示例代码
from playwright.sync_api import sync_playwright
# 上海悠悠 wx:283340479
# blog:https://www.cnblogs.com/yoyoketang/
with sync_playwright() as p:
browser = p.chromium.launch(headless=False)
context = browser.new_context()
page = context.new_page()
page.goto("http://127.0.0.1:8000/login.html")
page.locator('#username').fill('yoyo')
page.locator('#password').fill('******')
with page.expect_request('http://127.0.0.1:8000/api/login') as first:
page.locator('#loginBtn').click()
first_request = first.value
# 接口请求对象
print(first_request.url)
print(first_request.method)
# 获取接口返回内容
resp = first_request.response()
print(resp.status)
print(resp.json())
运行结果
http://127.0.0.1:8000/api/login
POST
400
{'message': '用户名或密码不正确'}
文章转自:https://www.cnblogs.com/yoyoketang/p/17721069.html