Skip to main content

Request

每当页面发送网络资源请求时,[页面] 会触发以下一系列事件:

🌐 Whenever the page sends a request for a network resource the following sequence of events are emitted by Page:

如果请求在某个阶段失败,那么会触发 page.on('requestfailed') 事件,而不是 'requestfinished' 事件(也可能不是 'response' 事件)。

🌐 If request fails at some point, then instead of 'requestfinished' event (and possibly instead of 'response' event), the page.on('requestfailed') event is emitted.

note

HTTP 错误响应,例如 404 或 503,从 HTTP 的角度来看仍然是成功的响应,因此请求将以 'requestfinished' 事件完成。:::

🌐 HTTP Error responses, such as 404 or 503, are still successful responses from HTTP standpoint, so request will complete with 'requestfinished' event.

如果请求收到“重定向”响应,请求会通过 requestfinished 事件成功完成,并且会向重定向的 URL 发起新的请求。

🌐 If request gets a 'redirect' response, the request is successfully finished with the requestfinished event, and a new request is issued to a redirected url.


方法

🌐 Methods

allHeaders

Added in: v1.15 request.allHeaders

一个包含与此请求关联的所有 HTTP 请求头的对象。头部名称为小写。

🌐 An object with all the request HTTP headers associated with this request. The header names are lower-cased.

用法

await request.allHeaders();

返回


failure

Added before v1.9 request.failure

除非该请求失败并由 requestfailed 事件报告,否则该方法返回 null

🌐 The method returns null unless this request has failed, as reported by requestfailed event.

用法

记录所有失败请求的示例:

🌐 Example of logging of all the failed requests:

page.on('requestfailed', request => {
console.log(request.url() + ' ' + request.failure().errorText);
});

返回

  • null | Object#
    • errorText string

      人类可读的错误信息,例如 'net::ERR_FAILED'


frame

Added before v1.9 request.frame

返回发起此请求的 Frame

🌐 Returns the Frame that initiated this request.

用法

const frameUrl = request.frame().url();

返回

详情

请注意,在某些情况下,框架不可用,此方法将抛出异常。

🌐 Note that in some cases the frame is not available, and this method will throw.

  • 当请求源自服务工作者时。你可以使用 request.serviceWorker() 来检查这一点。
  • 当在对应的框架创建之前发出导航请求时,可以使用 request.isNavigationRequest() 来检查这一点。

这是一个处理所有情况的示例:

🌐 Here is an example that handles all the cases:

if (request.serviceWorker())
console.log(`request ${request.url()} from a service worker`);
else if (request.isNavigationRequest())
console.log(`request ${request.url()} is a navigation request`);
else
console.log(`request ${request.url()} from a frame ${request.frame().url()}`);

headerValue

Added in: v1.15 request.headerValue

返回与名称匹配的头部的值。名称不区分大小写。

🌐 Returns the value of the header matching the name. The name is case-insensitive.

用法

await request.headerValue(name);

参数

返回


headers

Added before v1.9 request.headers

一个包含请求 HTTP 头的对象。头名称为小写。请注意,此方法不会返回与安全相关的头,包括与 cookie 相关的头。你可以使用 request.allHeaders() 获取包含 cookie 信息的完整头列表。

🌐 An object with the request HTTP headers. The header names are lower-cased. Note that this method does not return security-related headers, including cookie-related ones. You can use request.allHeaders() for complete list of headers that include cookie information.

用法

request.headers();

返回


headersArray

Added in: v1.15 request.headersArray

包含与此请求关联的所有请求 HTTP 头的数组。与 request.allHeaders() 不同,头名称不会被转换为小写。具有多个条目的头,例如 Set-Cookie,会在数组中出现多次。

🌐 An array with all the request HTTP headers associated with this request. Unlike request.allHeaders(), header names are NOT lower-cased. Headers with multiple entries, such as Set-Cookie, appear in the array multiple times.

用法

await request.headersArray();

返回


isNavigationRequest

Added before v1.9 request.isNavigationRequest

该请求是否驱动框架的导航。

🌐 Whether this request is driving frame's navigation.

有些导航请求是在相应的框架创建之前发出的,因此没有可用的 request.frame()

🌐 Some navigation requests are issued before the corresponding frame is created, and therefore do not have request.frame() available.

用法

request.isNavigationRequest();

返回


method

Added before v1.9 request.method

请求的方法(GET、POST 等)

🌐 Request's method (GET, POST, etc.)

用法

request.method();

返回


postData

Added before v1.9 request.postData

请求的帖子正文(如果有)。

🌐 Request's post body, if any.

用法

request.postData();

返回


postDataBuffer

Added before v1.9 request.postDataBuffer

二进制形式的请求的帖子正文(如果有)。

🌐 Request's post body in a binary form, if any.

用法

request.postDataBuffer();

返回


postDataJSON

Added before v1.9 request.postDataJSON

返回解析后的 form-urlencoded 请求体,如果有则以 JSON 作为备用。

🌐 Returns parsed request's body for form-urlencoded and JSON as a fallback if any.

当响应为 application/x-www-form-urlencoded 时,将返回一个包含这些值的键/值对象。否则,它将被解析为 JSON。

🌐 When the response is application/x-www-form-urlencoded then a key/value object of the values will be returned. Otherwise it will be parsed as JSON.

用法

request.postDataJSON();

返回


redirectedFrom

Added before v1.9 request.redirectedFrom

服务器重定向到此请求的请求(如果有)。

🌐 Request that was redirected by the server to this one, if any.

当服务器响应重定向时,Playwright 会创建一个新的 Request 对象。这两个请求通过 redirectedFrom()redirectedTo() 方法连接。当发生多个服务器重定向时,可以通过反复调用 redirectedFrom() 来构建整个重定向链。

🌐 When the server responds with a redirect, Playwright creates a new Request object. The two requests are connected by redirectedFrom() and redirectedTo() methods. When multiple server redirects has happened, it is possible to construct the whole redirect chain by repeatedly calling redirectedFrom().

用法

例如,如果网站 http://example.com 重定向到 https://example.com

🌐 For example, if the website http://example.com redirects to https://example.com:

const response = await page.goto('http://example.com');
console.log(response.request().redirectedFrom().url()); // 'http://example.com'

如果网站 https://google.com 没有重定向:

🌐 If the website https://google.com has no redirects:

const response = await page.goto('https://google.com');
console.log(response.request().redirectedFrom()); // null

返回


redirectedTo

Added before v1.9 request.redirectedTo

如果服务器以重定向响应,则浏览器触发新请求。

🌐 New request issued by the browser if the server responded with redirect.

用法

这个方法与 request.redirectedFrom() 相反:

🌐 This method is the opposite of request.redirectedFrom():

console.log(request.redirectedFrom().redirectedTo() === request); // true

返回


resourceType

Added before v1.9 request.resourceType

包含渲染引擎感知到的请求的资源类型。ResourceType 将是以下之一:documentstylesheetimagemediafontscripttexttrackxhrfetcheventsourcewebsocketmanifestother

🌐 Contains the request's resource type as it was perceived by the rendering engine. ResourceType will be one of the following: document, stylesheet, image, media, font, script, texttrack, xhr, fetch, eventsource, websocket, manifest, other.

用法

request.resourceType();

返回


response

Added before v1.9 request.response

返回匹配的 Response 对象,如果由于错误未收到响应,则返回 null

🌐 Returns the matching Response object, or null if the response was not received due to error.

用法

await request.response();

返回


serviceWorker

Added in: v1.24 request.serviceWorker

执行请求的服务工作进程

🌐 The Service Worker that is performing the request.

用法

request.serviceWorker();

返回

详情

此方法仅适用于 Chromium。使用其他浏览器时调用也是安全的,但它将始终返回 null

🌐 This method is Chromium only. It's safe to call when using other browsers, but it will always be null.

在服务工作进程中发起的请求没有可用的 request.frame()

🌐 Requests originated in a Service Worker do not have a request.frame() available.


sizes

Added in: v1.15 request.sizes

返回给定请求的资源大小信息。

🌐 Returns resource size information for given request.

用法

await request.sizes();

返回

  • Promise<Object>#
    • requestBodySize number

      请求体(POST 数据负载)的大小,以字节为单位。如果没有请求体,则设置为 0。

    • requestHeadersSize number

      从 HTTP 请求消息开始到(并包括)正文之前的双 CRLF 的总字节数。

    • responseBodySize number

      收到的响应正文(编码)的大小(以字节为单位)。

    • responseHeadersSize number

      从 HTTP 响应消息开始到(并包括)正文之前的双 CRLF 的总字节数。


timing

Added before v1.9 request.timing

返回给定请求的资源计时信息。大多数计时值在响应时可用,responseEnd 在请求完成时可用。更多信息请参见 资源计时 API

🌐 Returns resource timing information for given request. Most of the timing values become available upon the response, responseEnd becomes available when request finishes. Find more information at Resource Timing API.

用法

const requestFinishedPromise = page.waitForEvent('requestfinished');
await page.goto('http://example.com');
const request = await requestFinishedPromise;
console.log(request.timing());

返回

  • Object#
    • startTime number

      自 1970 年 1 月 1 日 00:00:00 UTC 以来经过的请求开始时间(以毫秒为单位)

    • domainLookupStart number

      浏览器开始为资源进行域名查找之前的时间。该值以相对于 startTime 的毫秒为单位,如果不可用则为 -1。

    • domainLookupEnd number

      浏览器启动后立即进行资源的域名查找的时间。该值以相对于 startTime 的毫秒为单位给出,如果不可用则为 -1。

    • connectStart number

      用户代理开始建立与服务器的连接以获取资源之前的时间。该值以相对于 startTime 的毫秒为单位,如果不可用则为 -1。

    • secureConnectionStart number

      浏览器开始握手过程以保护当前连接之前的时间。该值以相对于 startTime 的毫秒为单位给出,如果不可用则为 -1。

    • connectEnd number

      用户代理开始建立与服务器的连接以获取资源之前的时间。该值以相对于 startTime 的毫秒为单位,如果不可用则为 -1。

    • requestStart number

      浏览器开始从服务器、缓存或本地资源请求资源之前的时间。该值以相对于 startTime 的毫秒为单位表示,如果不可用则为 -1。

    • responseStart number

      浏览器从服务器、缓存或本地资源接收响应的第一个字节后立即使用时间。该值以毫秒为单位,相对于“startTime”,如果无法获得则为-1。

    • responseEnd number

      在浏览器接收到资源的最后一个字节之后或传输连接关闭之前(以先发生者为准)的时间。该值以相对于 startTime 的毫秒为单位表示,如果不可用则为 -1。


url

Added before v1.9 request.url

请求的 URL。

🌐 URL of the request.

用法

request.url();

返回