Skip to main content

请求

每当页面发送网络资源请求时,页面 就会触发以下事件序列:

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.

注意

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.

如果请求收到 'redirect' 响应,则该请求已成功完成并发生 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.

用法

Usage

await request.allHeaders();

返回

Returns


failure

Added in: v1.8 request.failure

该方法返回 null,除非此请求失败(如 requestfailed 事件所报告)。

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

用法

Usage

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

Example of logging of all the failed requests:

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

返回

Returns

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

Human-readable error message, e.g. 'net::ERR_FAILED'.


frame

Added in: v1.8 request.frame

返回发起此请求的 框架

Returns the Frame that initiated this request.

用法

Usage

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

返回

Returns

细节

Details

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

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

  • 当请求源自 Service Worker 时。你可以使用 request.serviceWorker() 来检查。

    When request originates in the Service Worker. You can use request.serviceWorker() to check that.

  • 在创建相应的框架之前触发导航请求时。你可以使用 request.isNavigationRequest() 来检查。

    When navigation request is issued before the corresponding frame is created. You can use request.isNavigationRequest() to check that.

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

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.

用法

Usage

await request.headerValue(name);

参数

Arguments

标头的名称。

Name of the header.

返回

Returns


headers

Added in: v1.8 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.

用法

Usage

request.headers();

返回

Returns


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.

用法

Usage

await request.headersArray();

返回

Returns

标头的名称。

Name of the header.

标头的值。

Value of the header.


isNavigationRequest

Added in: v1.8 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.

用法

Usage

request.isNavigationRequest();

返回

Returns


method

Added in: v1.8 request.method

请求的方法(GET、POST 等)

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

用法

Usage

request.method();

返回

Returns


postData

Added in: v1.8 request.postData

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

Request's post body, if any.

用法

Usage

request.postData();

返回

Returns


postDataBuffer

Added in: v1.8 request.postDataBuffer

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

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

用法

Usage

request.postDataBuffer();

返回

Returns


postDataJSON

Added in: v1.8 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.

用法

Usage

request.postDataJSON();

返回

Returns


redirectedFrom

Added in: v1.8 request.redirectedFrom

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

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

当服务器以重定向响应时,Playwright 创建一个新的 请求 对象。两个请求通过 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().

用法

Usage

例如,如果网站 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

返回

Returns


redirectedTo

Added in: v1.8 request.redirectedTo

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

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

用法

Usage

该方法与 request.redirectedFrom() 相反:

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

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

返回

Returns


resourceType

Added in: v1.8 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.

用法

Usage

request.resourceType();

返回

Returns


response

Added in: v1.8 request.response

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

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

用法

Usage

await request.response();

返回

Returns


serviceWorker

Added in: v1.24 request.serviceWorker

正在执行请求的服务 Worker

The Service Worker that is performing the request.

用法

Usage

request.serviceWorker();

返回

Returns

细节

Details

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

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

源自 Service Worker 的请求没有可用的 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.

用法

Usage

await request.sizes();

返回

Returns

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

Size of the request body (POST data payload) in bytes. Set to 0 if there was no body.

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

Total number of bytes from the start of the HTTP request message until (and including) the double CRLF before the body.

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

Size of the received response body (encoded) in bytes.

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

Total number of bytes from the start of the HTTP response message until (and including) the double CRLF before the body.


timing

Added in: v1.8 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.

用法

Usage

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

返回

Returns

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

Request start time in milliseconds elapsed since January 1, 1970 00:00:00 UTC

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

Time immediately before the browser starts the domain name lookup for the resource. The value is given in milliseconds relative to startTime, -1 if not available.

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

Time immediately after the browser starts the domain name lookup for the resource. The value is given in milliseconds relative to startTime, -1 if not available.

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

Time immediately before the user agent starts establishing the connection to the server to retrieve the resource. The value is given in milliseconds relative to startTime, -1 if not available.

  • secureConnectionStart number

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

Time immediately before the browser starts the handshake process to secure the current connection. The value is given in milliseconds relative to startTime, -1 if not available.

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

Time immediately before the user agent starts establishing the connection to the server to retrieve the resource. The value is given in milliseconds relative to startTime, -1 if not available.

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

Time immediately before the browser starts requesting the resource from the server, cache, or local resource. The value is given in milliseconds relative to startTime, -1 if not available.

浏览器从服务器、缓存或本地资源收到响应的第一个字节后的时间。该值以相对于 startTime 的毫秒为单位给出,如果不可用,则为 -1。

Time immediately after the browser receives the first byte of the response from the server, cache, or local resource. The value is given in milliseconds relative to startTime, -1 if not available.

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

Time immediately after the browser receives the last byte of the resource or immediately before the transport connection is closed, whichever comes first. The value is given in milliseconds relative to startTime, -1 if not available.


url

Added in: v1.8 request.url

请求的 URL。

URL of the request.

用法

Usage

request.url();

返回

Returns