Route对象
- 可以通过 page.route() 或者browser_context.route()来设置路由
- Route对象的方法有:
abort, continue_, fallback, fetch, fulfill
abort
终止路由请求, 并且可以设置error_code
,默认是failed
, 其他值有 aborted, accessdenied, connectionaborted, timeout
等
- 用法:
# 如果是图片类型终止请求
page.route("**/*", lambda route: route.abort() if route.request.resource_type == "image" else route.continue_())
# or
def handle_route(route, request):
if request.resource_type in ["image", "media", "websocket"]:
route.abort("aborted")
else:
route.continue_()
page.route("**/*", handle_route)
continue_
- 可选参数:
- headers: 请求头
- method: 请求方法,比如GET, POST, PUT 等
- post_data: 请求数据
- url: 请求url
- 用法:
修改以上参数值后,继续请求(modify requests)
# set headers
def handle(route, request):
# override headers
headers = {
**request.headers,
"foo": "foo-value", # set "foo" header
"bar": None # remove "bar" header
}
# del headers["bar"] # remove "bar" header
route.continue_(headers=headers)
# set url
def handle(route, request):
# override headers
url = request.url.replace("test", "test2")
route.continue_(url=url)
booking.page.route("**/api/abc**", handle) # 特定的请求包含/api/abc的请求中的 test替换为请求test2
fetch
执行请求并且返回结果, 返回值类型是 APIResponse
-
可选参数除了
headers, method, post_data, url
, 还有max_redirects, timeout
- max_redirects: 请求重定向的最大数量,默认是20
- timeout: 默认30s, 设置为0的话表示不会timeout
-
用法:在
fulfill
中
fulfill
- 可选参数:
- body: response body
- content_type: 响应类型
- headers: 响应头
- json: json response, 并且会设置content_type的值为
application/json
, 和body参数不能同时存在,会报错的(playwright 的1.29.0版本使用json参数这里有问题,用目前最新的1.37.0版本验证此问题已经解决) - path: 响应内容文件路径
- reponse: APIResponse to route reqest
- status: 响应状态,默认是200
- 用法:
修改响应数据
# 修改响应内容
page.route("**/search**", lambda route: route.fulfill(
content_type="text/plain",
body="page not found!"))
# 通过path修改响应内容
page.route("**/search**", lambda route: route.fulfill(path="test.json"))
# 通过json修改响应内容
def handle(route):
response = route.fetch()
r_json = response.json()
r_json["data"] = [] # 修改 响应内容中的data为[]
route.fulfill(response=response, json=r_json)
page.route("https://dog.ceo/api/breeds/list/all", handle)
fallback
- 可选参数同
continue_
的参数
unroute
- page.unroute() 可移除page.route()
- browser_context.unroute() 可移除browser_context.route()
- unroute的参数有
url, handler
,其中url参数必须要有, handler可选,如果handler没有值那么会移除到匹配的url的所有handler
参考文档: Route