Skip to main content

Route

每当使用 page.route()browser_context.route() 设置网络路由时,Route 对象可以用来处理该路由。

🌐 Whenever a network route is set up with page.route() or browser_context.route(), the Route object allows to handle the route.

了解更多关于网络的信息。

🌐 Learn more about networking.


方法

🌐 Methods

abort

Added before v1.9 route.abort

中止路由的请求。

🌐 Aborts the route's request.

用法

route.abort()
route.abort(**kwargs)

参数

  • error_code str (optional)#

    可选错误代码。默认为 failed,可以是以下之一:

    • 'aborted' - 操作已中止(由于用户操作)
    • 'accessdenied' - 访问资源(网络除外)的权限被拒绝
    • 'addressunreachable' - 该 IP 地址无法访问。这通常意味着没有通往指定主机或网络的路由。
    • 'blockedbyclient' - 客户端选择了阻止请求。
    • 'blockedbyresponse' - 请求失败,因为响应在附带不满足的要求的情况下被传送(例如 'X-Frame-Options' 和 'Content-Security-Policy' 的祖级检查)。
    • 'connectionaborted' - 由于未收到已发送数据的确认,应答(ACK),连接超时。
    • 'connectionclosed' - 一个连接已关闭(对应 TCP 的 FIN)。
    • 'connectionfailed' - 连接尝试失败。
    • 'connectionrefused' - 连接尝试被拒绝。
    • 'connectionreset' - 连接被重置(对应于 TCP RST)。
    • 'internetdisconnected' - 网络连接已断开。
    • 'namenotresolved' - 无法解析主机名称。
    • 'timedout' - 操作超时。
    • 'failed' - 发生了一般性故障。

返回


continue_

Added before v1.9 route.continue_

使用可选覆盖将路由的请求发送到网络。

🌐 Sends route's request to the network with optional overrides.

用法

def handle(route, request):
# override headers
headers = {
**request.headers,
"foo": "foo-value", # set "foo" header
"bar": None # remove "bar" header
}
route.continue_(headers=headers)

page.route("**/*", handle)

参数

  • headers Dict[str, str] (optional)#

    如果设置会更改请求的 HTTP 头。头部值将被转换为字符串。

  • method str (optional)#

    如果设置更改请求方法(例如 GET 或 POST)。

  • post_data str | bytes | Dict (optional)#

    如果设置更改请求的发布数据。

  • url str (optional)#

    如果设置更改请求 URL,则新 URL 必须与原始 URL 使用相同的协议。

返回

详情

headers 选项适用于路由请求及其发起的任何重定向。然而,urlmethodpost_data 仅适用于原始请求,并不会传递到重定向请求中。

🌐 The headers option applies to both the routed request and any redirects it initiates. However, url, method, and post_data only apply to the original request and are not carried over to redirected requests.

route.continue_() 会立即将请求发送到网络,其他匹配的处理程序将不会被调用。如果你希望调用链中的下一个匹配处理程序,请使用 route.fallback()

warning

某些请求头是禁止的,无法被覆盖(例如,CookieHostContent-Length 等,完整列表请参见 此 MDN 页面)。如果对禁止的请求头提供了覆盖,它将被忽略,并使用原始的请求头。

🌐 Some request headers are forbidden and cannot be overridden (for example, Cookie, Host, Content-Length and others, see this MDN page for full list). If an override is provided for a forbidden header, it will be ignored and the original request header will be used.

要设置自定义 Cookie,请使用 browser_context.add_cookies()

🌐 To set custom cookies, use browser_context.add_cookies().


fallback

Added in: v1.23 route.fallback

继续路由的请求,并可选择性地覆盖。该方法类似于 route.continue_(),不同之处在于会在发送请求之前调用其他匹配的处理程序。

🌐 Continues route's request with optional overrides. The method is similar to route.continue_() with the difference that other matching handlers will be invoked before sending the request.

用法

当多个路由匹配给定的模式时,它们会按与注册顺序相反的顺序运行。这样,最后注册的路由总是可以覆盖之前的所有路由。在下面的例子中,请求将首先由最底部的处理器处理,然后回退到之前的处理器,最终会被最先注册的路由中断。

🌐 When several routes match the given pattern, they run in the order opposite to their registration. That way the last registered route can always override all the previous ones. In the example below, request will be handled by the bottom-most handler first, then it'll fall back to the previous one and in the end will be aborted by the first registered route.

page.route("**/*", lambda route: route.abort())  # Runs last.
page.route("**/*", lambda route: route.fallback()) # Runs second.
page.route("**/*", lambda route: route.fallback()) # Runs first.

当你希望单独的处理程序处理不同类型的请求时,注册多个路由非常有用,例如 API 调用与页面资源或 GET 请求与 POST 请求(如下例所示)。

🌐 Registering multiple routes is useful when you want separate handlers to handle different kinds of requests, for example API calls vs page resources or GET requests vs POST requests as in the example below.

# Handle GET requests.
def handle_get(route):
if route.request.method != "GET":
route.fallback()
return
# Handling GET only.
# ...

# Handle POST requests.
def handle_post(route):
if route.request.method != "POST":
route.fallback()
return
# Handling POST only.
# ...

page.route("**/*", handle_get)
page.route("**/*", handle_post)

我们还可以在回退到后续处理程序时修改请求,这样中间路由处理程序就可以修改请求的 url、方法、标头和 postData。

🌐 One can also modify request while falling back to the subsequent handler, that way intermediate route handler can modify url, method, headers and postData of the request.

def handle(route, request):
# override headers
headers = {
**request.headers,
"foo": "foo-value", # set "foo" header
"bar": None # remove "bar" header
}
route.fallback(headers=headers)

page.route("**/*", handle)

使用 route.continue_() 可以立即将请求发送到网络,这种情况下其他匹配的处理程序将不会被调用。

🌐 Use route.continue_() to immediately send the request to the network, other matching handlers won't be invoked in that case.

参数

  • headers Dict[str, str] (optional)#

    如果设置会更改请求的 HTTP 头。头部值将被转换为字符串。

  • method str (optional)#

    如果设置更改请求方法(例如 GET 或 POST)。

  • post_data str | bytes | Dict (optional)#

    如果设置更改请求的发布数据。

  • url str (optional)#

    如果设置会更改请求 URL。新的 URL 必须与原始 URL 使用相同的协议。更改 URL 不会影响路由匹配,所有路由都是使用原始请求 URL 进行匹配的。

返回


fetch

Added in: v1.29 route.fetch

执行请求并获取结果而不执行它,以便可以修改响应然后执行。

🌐 Performs the request and fetches result without fulfilling it, so that the response could be modified and then fulfilled.

用法

def handle(route):
response = route.fetch()
json = response.json()
json["message"]["big_red_dog"] = []
route.fulfill(response=response, json=json)

page.route("https://dog.ceo/api/breeds/list/all", handle)

参数

  • headers Dict[str, str] (optional)#

    如果设置会更改请求的 HTTP 头。头部值将被转换为字符串。

  • max_redirects int (optional) Added in: v1.31#

    自动跟随的请求重定向的最大次数。如果超过该次数,将抛出错误。默认值为 20。传入 0 可不跟随重定向。

  • max_retries int (optional) Added in: v1.46#

    网络错误应重试的最大次数。目前仅重试 ECONNRESET 错误。不基于 HTTP 响应码进行重试。如果超过限制,将抛出错误。默认值为 0 - 不重试。

  • method str (optional)#

    如果设置更改请求方法(例如 GET 或 POST)。

  • post_data str | bytes | Dict (optional)#

    允许设置请求的 POST 数据。如果 data 参数是一个对象,它将被序列化为 JSON 字符串,并且如果未显式设置,content-type 头将被设置为 application/json。否则,如果未显式设置,content-type 头将被设置为 application/octet-stream

  • timeout float (optional) Added in: v1.33#

    请求超时时间(毫秒)。默认值为 30000(30 秒)。传入 0 可禁用超时。

  • url str (optional)#

    如果设置更改请求 URL,则新 URL 必须与原始 URL 使用相同的协议。

返回

详情

请注意,headers 选项将应用于获取的请求以及它引发的任何重定向。如果你只想将 headers 应用于原始请求,而不应用于重定向,请改用 route.continue_()

🌐 Note that headers option will apply to the fetched request as well as any redirects initiated by it. If you want to only apply headers to the original request, but not to redirects, look into route.continue_() instead.


fulfill

Added before v1.9 route.fulfill

通过给定的响应来满足路由的请求。

🌐 Fulfills route's request with given response.

用法

使用 404 响应满足所有请求的示例:

🌐 An example of fulfilling all requests with 404 responses:

page.route("**/*", lambda route: route.fulfill(
status=404,
content_type="text/plain",
body="not found!"))

提供静态文件的示例:

🌐 An example of serving static file:

page.route("**/xhr_endpoint", lambda route: route.fulfill(path="mock_data.json"))

参数

  • body str | bytes (optional)#

    响应体。

  • content_type str (optional)#

    如果设置,则等同于设置 Content-Type 响应头。

  • headers Dict[str, str] (optional)#

    响应头。头部值将被转换为字符串。

  • json Dict (optional) Added in: v1.29#

    JSON 响应。如果未设置,此方法将把内容类型设置为 application/json

  • path Union[str, pathlib.Path] (optional)#

    要响应的文件路径。内容类型将根据文件扩展名推断。如果 path 是相对路径,则相对于当前工作目录进行解析。

  • response APIResponse (optional) Added in: v1.15#

    APIResponse 用于满足路由的请求。可以使用 fulfill 选项覆盖响应的各个字段(例如 headers)。

  • status int (optional)#

    响应状态码,默认为 200

返回


属性

🌐 Properties

request

Added before v1.9 route.request

要路由的请求。

🌐 A request to be routed.

用法

route.request

返回