Skip to main content
Version: 25.3.0

Page 类

🌐 Page class

页面提供了与浏览器中的单个标签页或扩展后台页面交互的方法。

🌐 Page provides methods to interact with a single tab or extension background page in the browser.

note

一个浏览器实例可能有多个页面实例。

🌐 One Browser instance might have multiple Page instances.

语法

🌐 Signature

export declare abstract class Page extends EventEmitter<PageEvents>

Extends: EventEmitter<PageEvents>

附注

🌐 Remarks

这个类的构造函数被标记为内部。第三方代码不应直接调用构造函数或创建继承 Page 类的子类。

🌐 The constructor for this class is marked as internal. Third-party code should not call the constructor directly or create subclasses that extend the Page class.

示例 1

🌐 Example 1

此示例创建一个页面,将其导航到 URL,然后保存屏幕截图:

🌐 This example creates a page, navigates it to a URL, and then saves a screenshot:

import puppeteer from 'puppeteer';

const browser = await puppeteer.launch();
const page = await browser.newPage();
await page.goto('https://example.com');
await page.screenshot({path: 'screenshot.png'});
await browser.close();

Page 类继承自 Puppeteer 的 EventEmitter 类,并将触发在 PageEvent 枚举中记录的各种事件。

🌐 The Page class extends from Puppeteer's EventEmitter class and will emit various events which are documented in the PageEvent enum.

示例 2

🌐 Example 2

此示例记录单页 load 事件的消息:

🌐 This example logs a message for a single page load event:

page.once('load', () => console.log('Page loaded!'));

要取消订阅事件,请使用 EventEmitter.off() 方法:

🌐 To unsubscribe from events use the EventEmitter.off() method:

function logRequest(interceptedRequest) {
console.log('A request was made:', interceptedRequest.url());
}
page.on('request', logRequest);
// Sometime later...
page.off('request', logRequest);

属性

🌐 Properties

属性

🌐 Property

修饰符

🌐 Modifiers

类型

🌐 Type

描述

🌐 Description

accessibility

readonly

无障碍

Accessibility 类提供了用于检查浏览器可访问性树的方法。可访问性树被辅助技术使用,例如屏幕阅读器开关

🌐 The Accessibility class provides methods for inspecting the browser's accessibility tree. The accessibility tree is used by assistive technology such as screen readers or switches.

附注

无障碍性是一个非常依赖平台的事情。在不同的平台上,可能有不同的屏幕阅读器,其输出可能差异很大。

🌐 Accessibility is a very platform-specific thing. On different platforms, there are different screen readers that might have wildly different output.

Blink——Chrome 的渲染引擎——有一个“可访问性树”的概念,然后将其转换为不同平台特定的 API。可访问性命名空间使用户能够访问 Blink 可访问性树。

🌐 Blink - Chrome's rendering engine - has a concept of "accessibility tree", which is then translated into different platform-specific APIs. Accessibility namespace gives users access to the Blink Accessibility Tree.

在从 Blink AX 树转换为特定平台的 AX 树或由辅助技术本身进行转换时,大部分可访问性树会被过滤掉。默认情况下,Puppeteer 会尝试近似这种过滤,只公开树中“有趣”的节点。

🌐 Most of the accessibility tree gets filtered out when converting from Blink AX Tree to Platform-specific AX-Tree or by assistive technologies themselves. By default, Puppeteer tries to approximate this filtering, exposing only the "interesting" nodes of the tree.

这个类的构造函数被标记为内部。第三方代码不应直接调用构造函数或创建继承 Accessibility 类的子类。

🌐 The constructor for this class is marked as internal. Third-party code should not call the constructor directly or create subclasses that extend the Accessibility class.

bluetooth

readonly

蓝牙模拟

启用蓝牙模拟功能。

🌐 Exposes the bluetooth emulation abilities.

附注

Web Bluetooth 规范 要求模拟适配器应按顶层可导航对象进行隔离。然而,目前 Chromium 的蓝牙模拟实现是绑定到浏览器上下文,而不是页面。这意味着从同一浏览器上下文的不同页面暴露的蓝牙模拟会相互干扰它们的状态。

coverage

readonly

覆盖范围

Coverage 类提供了收集有关页面所使用的 JavaScript 和 CSS 部分的信息的方法。

🌐 The Coverage class provides methods to gather information about parts of JavaScript and CSS that were used by the page.

附注

要以 Istanbul 可使用的格式输出覆盖率,请参阅 puppeteer-to-istanbul

🌐 To output coverage in a form consumable by Istanbul, see puppeteer-to-istanbul.

这个类的构造函数被标记为内部。第三方代码不应直接调用构造函数或创建继承 Coverage 类的子类。

🌐 The constructor for this class is marked as internal. Third-party code should not call the constructor directly or create subclasses that extend the Coverage class.

keyboard

readonly

键盘

Keyboard 提供了一个用于管理虚拟键盘的 API。高级 API 是 Keyboard.type(),它接收原始字符并在你的页面上生成适当的 keydown、keypress/input 和 keyup 事件。

🌐 Keyboard provides an api for managing a virtual keyboard. The high level api is Keyboard.type(), which takes raw characters and generates proper keydown, keypress/input, and keyup events on your page.

附注

为了更精细的控制,你可以使用 Keyboard.down()Keyboard.up()Keyboard.sendCharacter() 来手动触发事件,就像它们是由真实键盘生成的一样。

🌐 For finer control, you can use Keyboard.down(), Keyboard.up(), and Keyboard.sendCharacter() to manually fire events as if they were generated from a real keyboard.

在 macOS 上,像 ⌘ A -> 全选 这样的键盘快捷键不能使用。请参见 #1313

🌐 On macOS, keyboard shortcuts like ⌘ A -> Select All do not work. See #1313.

这个类的构造函数被标记为内部。第三方代码不应直接调用构造函数或创建继承 Keyboard 类的子类。

🌐 The constructor for this class is marked as internal. Third-party code should not call the constructor directly or create subclasses that extend the Keyboard class.

mouse

readonly

鼠标

Mouse 类在相对于视口左上角的主框架 CSS 像素中运行。

🌐 The Mouse class operates in main-frame CSS pixels relative to the top-left corner of the viewport.

附注

每个 page 对象都有自己的鼠标,可以通过 Page.mouse 访问。

🌐 Every page object has its own Mouse, accessible with Page.mouse.

这个类的构造函数被标记为内部。第三方代码不应直接调用构造函数或创建继承 Mouse 类的子类。

🌐 The constructor for this class is marked as internal. Third-party code should not call the constructor directly or create subclasses that extend the Mouse class.

touchscreen

readonly

触摸屏

Touchscreen 类公开触摸屏事件。

🌐 The Touchscreen class exposes touchscreen events.

tracing

readonly

追踪

Tracing 类公开跟踪审计接口。

🌐 The Tracing class exposes the tracing audit interface.

附注

你可以使用 tracing.starttracing.stop 创建一个 trace 文件,该文件可以在 Chrome 开发者工具或 timeline viewer 中打开。

🌐 You can use tracing.start and tracing.stop to create a trace file which can be opened in Chrome DevTools or timeline viewer.

这个类的构造函数被标记为内部。第三方代码不应直接调用构造函数或创建继承 Tracing 类的子类。

🌐 The constructor for this class is marked as internal. Third-party code should not call the constructor directly or create subclasses that extend the Tracing class.

webmcp

readonly

WebMCP

(实验性) 针对 WebMCP 的实验性 API。需要 Chrome 150 以上版本,并启用 --enable-features=WebMCP 标志。

方法

🌐 Methods

方法

🌐 Method

修饰符

🌐 Modifiers

描述

🌐 Description

$(selector)

找到与选择器匹配的第一个元素。如果没有元素与选择器匹配,返回值解析为 null

🌐 Finds the first element that matches the selector. If no element matches the selector, the return value resolves to null.

附注

Page.mainFrame().$(selector) 的快捷方式。

🌐 Shortcut for Page.mainFrame().$(selector).

$$(selector, options)

在页面上查找与选择器匹配的元素。如果没有元素匹配选择器,返回值将解析为 []

🌐 Finds elements on the page that match the selector. If no elements match the selector, the return value resolves to [].

附注

Page.mainFrame().$$(selector) 的快捷方式。

🌐 Shortcut for Page.mainFrame().$$(selector).

$$eval(selector, pageFunction, args)

此方法返回与选择器匹配的所有元素,并将结果数组作为第一个参数传递给 pageFunction

🌐 This method returns all elements matching the selector and passes the resulting array as the first argument to the pageFunction.

附注

如果 pageFunction 返回一个 promise,$$eval 将等待该 promise 解决,然后返回其值。

🌐 If pageFunction returns a promise $$eval will wait for the promise to resolve and then return its value.

$eval(selector, pageFunction, args)

此方法查找页面中第一个与选择器匹配的元素,并将结果作为第一个参数传递给 pageFunction

🌐 This method finds the first element within the page that matches the selector and passes the result as the first argument to the pageFunction.

附注

如果未找到匹配 selector 的元素,该方法将抛出错误。

🌐 If no element is found matching selector, the method will throw an error.

如果 pageFunction 返回一个 promise,$eval 将等待该 promise 解决,然后返回其值。

🌐 If pageFunction returns a promise $eval will wait for the promise to resolve and then return its value.

addScriptTag(options)

在页面中添加一个 <script> 标签,包含所需的 URL 或内容。

🌐 Adds a <script> tag into the page with the desired URL or content.

附注

page.mainFrame().addScriptTag(options) 的快捷方式。

🌐 Shortcut for page.mainFrame().addScriptTag(options).

addStyleTag(options)

在页面中添加一个带有所需 URL 的 <link rel="stylesheet"> 标签,或一个带有内容的 <style type="text/css"> 标签。

🌐 Adds a <link rel="stylesheet"> tag into the page with the desired URL or a <style type="text/css"> tag with the content.

page.mainFrame().addStyleTag(options) 的快捷方式。

🌐 Shortcut for page.mainFrame().addStyleTag(options).

addStyleTag(options)
authenticate(credentials)

提供 HTTP authentication 的凭据。

🌐 Provide credentials for HTTP authentication.

note

请求拦截将在后台开启以实现身份验证。这可能会影响性能。

🌐 Request interception will be turned on behind the scenes to implement authentication. This might affect performance.

附注

要禁用身份验证,请传递 null

🌐 To disable authentication, pass null.

bringToFront()

将页面置于前面(激活选项卡)。

🌐 Brings page to front (activates tab).

browser()

获取页面所属的浏览器。

🌐 Get the browser the page belongs to.

browserContext()

获取页面所属的浏览器上下文。

🌐 Get the browser context that the page belongs to.

captureHeapSnapshot(options)

捕获 JavaScript 堆的快照并将其写入文件。

🌐 Captures a snapshot of the JavaScript heap and writes it to a file.

click(selector, options)

此方法获取具有 selector 的元素,如果需要,会将其滚动到可见区域,然后使用 Page.mouse 在元素中心点击。如果没有匹配 selector 的元素,该方法会抛出错误。

🌐 This method fetches an element with selector, scrolls it into view if needed, and then uses Page.mouse to click in the center of the element. If there's no element matching selector, the method throws an error.

附注

请记住,如果 click() 触发了导航事件,同时还有一个单独的 page.waitForNavigation() Promise 需要被解决,你可能会遇到导致意外结果的竞争条件。点击并等待导航的正确模式如下:

🌐 Bear in mind that if click() triggers a navigation event and there's a separate page.waitForNavigation() promise to be resolved, you may end up with a race condition that yields unexpected results. The correct pattern for click and wait for navigation is the following:

const [response] = await Promise.all([
page.waitForNavigation(waitOptions),
page.click(selector, clickOptions),
]);

page.mainFrame().click(selector[, options]) 的快捷方式。

🌐 Shortcut for page.mainFrame().click(selector[, options]).

close(options)
content()

页面的完整 HTML 内容,包括 DOCTYPE。

🌐 The full HTML contents of the page, including the DOCTYPE.

cookies(urls)

deprecated

如果未指定 URL,此方法将返回当前页面 URL 的 Cookie。如果指定了 URL,则仅返回这些 URL 的 Cookie。

🌐 If no URLs are specified, this method returns cookies for the current page URL. If URLs are specified, only cookies for those URLs are returned.

已弃用:

页面级别的 cookie API 已被弃用。请改用 Browser.cookies()BrowserContext.cookies()

🌐 Page-level cookie API is deprecated. Use Browser.cookies() or BrowserContext.cookies() instead.

createCDPSession()

创建附加到页面的 Chrome Devtools 协议会话。

🌐 Creates a Chrome Devtools Protocol session attached to the page.

createPDFStream(options)

生成具有 print CSS 媒体类型的页面 PDF。

🌐 Generates a PDF of the page with the print CSS media type.

附注

要使用 screen 媒体类型生成 PDF,请在调用 page.pdf() 之前调用 page.emulateMediaType('screen')\

🌐 To generate a PDF with the screen media type, call `page.emulateMediaType('screen')` before calling page.pdf().

默认情况下,page.pdf() 会生成用于打印的颜色已修改的 PDF。使用 -webkit-print-color-adjust\ 属性可以强制渲染精确的颜色。

🌐 By default, page.pdf() generates a pdf with modified colors for printing. Use the `-webkit-print-color-adjust` property to force rendering of exact colors.

deleteCookie(cookies)

deprecated

已弃用:

页面级别的 cookie API 已被弃用。请改用 Browser.deleteCookie()BrowserContext.deleteCookie()Browser.deleteMatchingCookies()BrowserContext.deleteMatchingCookies()

🌐 Page-level cookie API is deprecated. Use Browser.deleteCookie(), BrowserContext.deleteCookie(), Browser.deleteMatchingCookies() or BrowserContext.deleteMatchingCookies() instead.

emulate(device)

模拟给定设备的指标和用户代理。

🌐 Emulates a given device's metrics and user agent.

为了辅助模拟,Puppeteer 提供了一份已知设备的列表,可以通过 KnownDevices 访问。

🌐 To aid emulation, Puppeteer provides a list of known devices that can be via KnownDevices.

附注

这种方法是调用两个方法的捷径:Page.setUserAgent()Page.setViewport()

🌐 This method is a shortcut for calling two methods: Page.setUserAgent() and Page.setViewport().

此方法将调整页面大小。许多网站不期望手机改变大小,因此你应该在导航到页面之前进行模拟。

🌐 This method will resize the page. A lot of websites don't expect phones to change size, so you should emulate before navigating to the page.

emulateCPUThrottling(factor)

启用 CPU 限制以模拟慢速 CPU。

🌐 Enables CPU throttling to emulate slow CPUs.

emulateFocusedPage(enabled)

模拟页面的焦点状态。

🌐 Emulates focus state of the page.

emulateIdleState(overrides)

模拟空闲状态。如果未设置任何参数,则清除空闲状态模拟。

🌐 Emulates the idle state. If no arguments set, clears idle state emulation.

emulateLocale(locale)
emulateMediaFeatures(features)
emulateMediaType(type)
emulateNetworkConditions(networkConditions)

这不会影响 WebSockets 和 WebRTC PeerConnections(参见 https://crbug.com/563644)。要将页面设置为离线,可以使用 Page.setOfflineMode()

🌐 This does not affect WebSockets and WebRTC PeerConnections (see https://crbug.com/563644). To set the page offline, you can use Page.setOfflineMode().

可以通过导入 PredefinedNetworkConditions 来使用预定义的网络条件列表。

🌐 A list of predefined network conditions can be used by importing PredefinedNetworkConditions.

emulateTimezone(timezoneId)
emulateVisionDeficiency(type)

模拟页面上给定的视力缺陷。

🌐 Simulates the given vision deficiency on the page.

evaluate(pageFunction, args)

评估页面上下文中的函数并返回结果。

🌐 Evaluates a function in the page's context and returns the result.

如果传递给 page.evaluate 的函数返回一个 Promise,该函数将等待该 Promise 被解决并返回其值。

🌐 If the function passed to page.evaluate returns a Promise, the function will wait for the promise to resolve and return its value.

evaluateHandle(pageFunction, args)

附注

page.evaluatepage.evaluateHandle 唯一的区别在于 evaluateHandle 会返回封装在页面内对象中的值。

🌐 The only difference between page.evaluate and page.evaluateHandle is that evaluateHandle will return the value wrapped in an in-page object.

如果传递给 page.evaluateHandle 的函数返回一个 Promise,该函数将等待该 Promise 被解决并返回其值。

🌐 If the function passed to page.evaluateHandle returns a Promise, the function will wait for the promise to resolve and return its value.

你可以传递字符串而不是函数(尽管建议使用函数,因为它们更容易调试并与 TypeScript 一起使用):

🌐 You can pass a string instead of a function (although functions are recommended as they are easier to debug and use with TypeScript):

evaluateOnNewDocument(pageFunction, args)

添加将在以下场景之一调用的函数:

🌐 Adds a function which would be invoked in one of the following scenarios:

  • 每当页面被导航时
  • 每当子帧被附加或导航时。在这种情况下,该函数会在新附加的帧的上下文中被调用。

该函数在文档创建后但在其任何脚本运行之前被调用。这对于修改 JavaScript 环境很有用,例如,初始化 Math.random

🌐 The function is invoked after the document was created but before any of its scripts were run. This is useful to amend the JavaScript environment, e.g. to seed Math.random.

exposeFunction(name, pptrFunction)

该方法在页面的 window 对象上添加了一个名为 name 的函数。调用该函数时,会在 node.js 中执行 puppeteerFunction,并返回一个 Promise,该 Promise 解析为 puppeteerFunction 的返回值。

🌐 The method adds a function called name on the page's window object. When called, the function executes puppeteerFunction in node.js and returns a Promise which resolves to the return value of puppeteerFunction.

如果 puppeteerFunction 返回一个 Promise,它将被等待。

🌐 If the puppeteerFunction returns a Promise, it will be awaited.

note

通过 page.exposeFunction 安装的函数在导航过程中能够保留。

🌐 Functions installed via page.exposeFunction survive navigations.

extensionRealms()

检索页面主框架中扩展执行域的列表。这些域对应于在页面上运行的扩展内容脚本。

🌐 Retrieves the list of extension execution realms in the main frame of the page. These realms correspond to extension content scripts running on the page.

mainFrame().extensionRealms() 的快捷方式。

🌐 Shortcut for mainFrame().extensionRealms().

focus(selector)

该方法获取带有 selector 的元素并将其聚焦。如果没有匹配 selector 的元素,该方法会抛出错误。

🌐 This method fetches an element with selector and focuses it. If there's no element matching selector, the method throws an error.

附注

page.mainFrame().focus(selector) 的快捷方式。

🌐 Shortcut for page.mainFrame().focus(selector).

frames()

附加到页面的所有框架的数组。

🌐 An array of all frames attached to the page.

getDefaultNavigationTimeout()

最大导航时间(以毫秒为单位)。

🌐 Maximum navigation time in milliseconds.

getDefaultTimeout()

最长时间(以毫秒为单位)。

🌐 Maximum time in milliseconds.

goBack(options)

此方法导航到历史记录中的上一页。

🌐 This method navigate to the previous page in history.

goForward(options)

此方法导航到历史记录的下一页。

🌐 This method navigate to the next page in history.

goto(url, options)

将框架或页面导航到指定的 url

🌐 Navigates the frame or page to the given url.

附注

导航到 about:blank 或导航到带有不同哈希的相同 URL 将成功并返回 null

🌐 Navigation to about:blank or navigation to the same URL with a different hash will succeed and return null.

warning

无头浏览器模式不支持导航到 PDF 文档。请参见 上游问题

🌐 Headless shell mode doesn't support navigation to a PDF document. See the upstream issue.

在无头浏览器中,当远程服务器返回任何有效的HTTP状态码时,包括404 “未找到”和500 “内部服务器错误”,此方法不会抛出错误。可以通过调用HTTPResponse.status()来获取此类响应的状态码。

🌐 In headless shell, this method will not throw an error when any valid HTTP status code is returned by the remote server, including 404 "Not Found" and 500 "Internal Server Error". The status code for such responses can be retrieved by calling HTTPResponse.status().

hasDevTools()

(实验) 如果 DevTools 附加到当前页面,则返回 true。使用 Page.openDevTools() 来获取 DevTools 页面。

hover(selector)

此方法获取一个带有 selector 的元素,如果需要会将其滚动到视图中,然后使用 Page.mouse 悬停在元素的中心。如果没有匹配 selector 的元素,该方法将抛出错误。

🌐 This method fetches an element with selector, scrolls it into view if needed, and then uses Page.mouse to hover over the center of the element. If there's no element matching selector, the method throws an error.

附注

page.mainFrame().hover(selector) 的快捷方式。

🌐 Shortcut for page.mainFrame().hover(selector).

isClosed()

表示该页面已关闭。

🌐 Indicates that the page has been closed.

isDragInterceptionEnabled()

deprecated

true 如果拖拽事件被拦截,否则为 false

已弃用:

我们不再支持拦截拖动负载。请使用 ElementHandle 上的新拖动 API 进行拖动(或者直接使用 Page.mouse)。

🌐 We no longer support intercepting drag payloads. Use the new drag APIs found on ElementHandle to drag (or just use the Page.mouse).

isJavaScriptEnabled()

如果页面启用了 JavaScript,则显示 true,否则显示 false

isServiceWorkerBypassed()

如果服务工作者被绕过,则为 true,否则为 false

locator(selector)

为提供的选择器创建一个定位器。有关详细信息和支持的操作,请参见 Locator

🌐 Creates a locator for the provided selector. See Locator for details and supported actions.

locator(func)

为提供的函数创建一个定位器。详情和支持的操作请参见 Locator

🌐 Creates a locator for the provided function. See Locator for details and supported actions.

mainFrame()

页面的主框架。

🌐 The page's main frame.

metrics()

包含指标作为键/值对的对象。

🌐 Object containing metrics as key/value pairs.

附注

所有时间戳都是单调时间:自过去任意点起按秒单调增加的时间。

🌐 All timestamps are in monotonic time: monotonically increasing time in seconds since an arbitrary point in the past.

openDevTools()

如果尚未打开,会为此页面打开开发者工具并返回开发者工具页面。此方法仅在 Chrome 中可用。

🌐 Opens DevTools for the this page if not already open and returns the DevTools page. This method is only available in Chrome.

pdf(options)

生成具有 print CSS 媒体类型的页面 PDF。

🌐 Generates a PDF of the page with the print CSS media type.

附注

要使用 screen 媒体类型生成 PDF,请在调用 page.pdf() 之前调用 page.emulateMediaType('screen')\

🌐 To generate a PDF with the screen media type, call `page.emulateMediaType('screen')` before calling page.pdf().

默认情况下,page.pdf() 会生成用于打印的颜色已修改的 PDF。使用 -webkit-print-color-adjust\ 属性可以强制渲染精确的颜色。

🌐 By default, page.pdf() generates a pdf with modified colors for printing. Use the `-webkit-print-color-adjust` property to force rendering of exact colors.

queryObjects(prototypeHandle)

此方法迭代 JavaScript 堆并查找具有给定原型的所有对象。

🌐 This method iterates the JavaScript heap and finds all objects with the given prototype.

reload(options)

重新加载页面。

🌐 Reloads the page.

removeExposedFunction(name)

该方法通过页面的 window 对象从之前添加的函数 $[Page.exposeFunction()](./puppeteer.page.exposefunction.md) 中移除名为 name 的函数。

🌐 The method removes a previously added function via $Page.exposeFunction() called name from the page's window object.

removeScriptToEvaluateOnNewDocument(identifier)

删除通过 Page.evaluateOnNewDocument 注入页面的脚本。

🌐 Removes script that injected into page by Page.evaluateOnNewDocument.

resize(params)

(实验性) 调整此页面的浏览器窗口大小,使内容区域(不包括浏览器界面)具有指定的宽度和高度。

screencast(options)

(实验性) 捕捉此 页面 的屏幕录制。

附注

默认情况下,所有录音将使用 VP9 视频编解码器的 WebM 格式,帧率为 30 FPS。

🌐 By default, all recordings will be WebM format using the VP9 video codec, with a frame rate of 30 FPS.

你的系统中必须安装 ffmpeg

🌐 You must have ffmpeg installed on your system.

screenshot(options)

捕获此页面的截图。

🌐 Captures a screenshot of this page.

附注

BrowserContext 中截取屏幕截图时,以下方法将自动等待屏幕截图完成,以防干扰屏幕截图过程:BrowserContext.newPage()Browser.newPage()Page.close()

🌐 While a screenshot is being taken in a BrowserContext, the following methods will automatically wait for the screenshot to finish to prevent interference with the screenshot process: BrowserContext.newPage(), Browser.newPage(), Page.close().

调用 Page.bringToFront() 不会等待现有的截图操作。

🌐 Calling Page.bringToFront() will not wait for existing screenshot operations.

screenshot(options)
select(selector, values)

一旦所有提供的选项都被选择,会触发 changeinput 事件。如果没有匹配 selector<select> 元素,该方法将抛出错误。

🌐 Triggers a change and input event once all the provided options have been selected. If there's no <select> element matching selector, the method throws an error.

附注

page.mainFrame().select() 的快捷方式

🌐 Shortcut for page.mainFrame().select()

setBypassCSP(enabled)

切换绕过页面的内容安全策略。

🌐 Toggles bypassing page's Content-Security-Policy.

附注

注意:CSP 绕过发生在 CSP 初始化的时刻,而不是评估时。通常,这意味着应在导航到该域之前调用 page.setBypassCSP

🌐 NOTE: CSP bypassing happens at the moment of CSP initialization rather than evaluation. Usually, this means that page.setBypassCSP should be called before navigating to the domain.

setBypassServiceWorker(bypass)

切换忽略每个请求的 Service Worker。

🌐 Toggles ignoring of service worker for each request.

setCacheEnabled(enabled)

根据启用状态切换每个请求是否忽略缓存。默认情况下,缓存是启用的。

🌐 Toggles ignoring cache for each request based on the enabled state. By default, caching is enabled.

setContent(html, options)

设置页面的内容。

🌐 Set the content of the page.

setCookie(cookies)

deprecated

已弃用:

页面级 cookie API 已被弃用。请改用 Browser.setCookie()BrowserContext.setCookie()

🌐 Page-level cookie API is deprecated. Use Browser.setCookie() or BrowserContext.setCookie() instead.

setDefaultNavigationTimeout(timeout)

此设置将更改以下方法和相关快捷方式的默认最大导航时间:

🌐 This setting will change the default maximum navigation time for the following methods and related shortcuts:

setDefaultTimeout(timeout)
setDragInterception(enabled)

deprecated

已弃用:

我们不再支持拦截拖动负载。请使用 ElementHandle 上的新拖动 API 进行拖动(或者直接使用 Page.mouse)。

🌐 We no longer support intercepting drag payloads. Use the new drag APIs found on ElementHandle to drag (or just use the Page.mouse).

setExtraHTTPHeaders(headers)

额外的 HTTP 标头将随页面发起的每个请求一起发送。

🌐 The extra HTTP headers will be sent with every request the page initiates.

tip

所有 HTTP 头名称都使用小写。(HTTP 头不区分大小写,因此这不应影响你的服务器代码。)

🌐 All HTTP header names are lowercased. (HTTP headers are case-insensitive, so this shouldn’t impact your server code.)

note

page.setExtraHTTPHeaders 不保证传出请求中标头的顺序。

🌐 page.setExtraHTTPHeaders does not guarantee the order of headers in the outgoing requests.

setGeolocation(options)

设置页面的地理位置。

🌐 Sets the page's geolocation.

附注

考虑使用 BrowserContext.overridePermissions() 来授予页面读取其地理位置的权限。

🌐 Consider using BrowserContext.overridePermissions() to grant permissions for the page to read its geolocation.

setJavaScriptEnabled(enabled)

附注

注意:更改此值不会影响已经运行的脚本。它将在下一次导航时完全生效。

🌐 NOTE: changing this value won't affect scripts that have already been run. It will take full effect on the next navigation.

setOfflineMode(enabled)

模拟离线模式。

🌐 Emulates the offline mode.

它不会更改由 Page.emulateNetworkConditions() 设置的下载/上传/延迟参数

🌐 It does not change the download/upload/latency parameters set by Page.emulateNetworkConditions()

setRequestInterception(value)

启用请求拦截后,可以使用 HTTPRequest.abort()HTTPRequest.continue()HTTPRequest.respond() 方法。这提供了修改页面发出的网络请求的能力。

🌐 Activating request interception enables HTTPRequest.abort(), HTTPRequest.continue() and HTTPRequest.respond() methods. This provides the capability to modify network requests that are made by a page.

一旦启用请求拦截,除非请求被继续、响应或中止,否则每个请求都会暂停;或者使用浏览器缓存完成。

🌐 Once request interception is enabled, every request will stall unless it's continued, responded or aborted; or completed using the browser cache.

有关详细信息,请参见 请求拦截指南

🌐 See the Request interception guide for more details.

setUserAgent(userAgent, userAgentMetadata)

deprecated

已弃用:

请改用 Page.setUserAgent()

🌐 Use Page.setUserAgent() instead.

setUserAgent(options)
setViewport(viewport)

page.setViewport 将调整页面大小。许多网站没有预料到手机会改变尺寸,因此你应该在导航到页面之前设置视口。

在单个浏览器中有多个页面的情况下,每个页面可以有自己的视口大小。将视口设置为 null 会将视口重置为默认值。

🌐 In the case of multiple pages in a single browser, each page can have its own viewport size. Setting the viewport to null resets the viewport to its default value.

附注

注意:在某些情况下,设置视口会重新加载页面,以便设置 isMobile 或 hasTouch 属性。

🌐 NOTE: in certain cases, setting viewport will reload the page in order to set the isMobile or hasTouch properties.

tap(selector)

该方法获取一个带有 selector 的元素,必要时将其滚动到可见区域,然后使用 Page.touchscreen 点击元素中心。如果没有匹配 selector 的元素,该方法将抛出错误。

🌐 This method fetches an element with selector, scrolls it into view if needed, and then uses Page.touchscreen to tap in the center of the element. If there's no element matching selector, the method throws an error.

附注

page.mainFrame().tap(selector) 的快捷方式。

🌐 Shortcut for page.mainFrame().tap(selector).

target()

deprecated

创建此页面的目标。

🌐 A target this page was created from.

已弃用:

要创建 CDP 会话,请直接使用 Page.createCDPSession()。要识别由此页面产生的页面,请改用 PageEvent.Popup 事件。

🌐 To create CDP session use Page.createCDPSession() directly. To identify pages spawned by this one, use PageEvent.Popup event instead.

title()

页面的标题

🌐 The page's title

附注

page.mainFrame().title() 的快捷方式。

🌐 Shortcut for page.mainFrame().title().

triggerExtensionAction(extension)

触发此页面指定扩展程序的默认操作。这相当于在浏览器工具栏中点击扩展程序的图标。

🌐 Triggers the default action of the specified extension for this page. This simulates clicking the extension's icon in the browser's toolbar.

type(selector, text, options)

对文本中的每个字符发送一个 keydownkeypress/inputkeyup 事件。

🌐 Sends a keydown, keypress/input, and keyup event for each character in the text.

要按下特殊键,例如 ControlArrowDown,请使用 Keyboard.press()

🌐 To press a special key, like Control or ArrowDown, use Keyboard.press().

url()

页面的 URL。

🌐 The page's URL.

附注

page.mainFrame().url() 的快捷方式。

🌐 Shortcut for page.mainFrame().url().

viewport()

返回当前页面视口设置,而不检查实际页面视口。

🌐 Returns the current page viewport settings without checking the actual page viewport.

这是通过先前的 Page.setViewport() 调用设置的视口,或者通过 ConnectOptions.defaultViewport 设置的默认视口。

🌐 This is either the viewport set with the previous Page.setViewport() call or the default viewport set via ConnectOptions.defaultViewport.

waitForDevicePrompt(options)

此方法通常与从 API(例如 WebBluetooth)触发设备请求的操作结合使用。

🌐 This method is typically coupled with an action that triggers a device request from an api such as WebBluetooth.

caution

在发出设备请求之前必须调用此方法。它不会返回当前处于活动状态的设备提示。

🌐 This must be called before the device request is made. It will not return a currently active device prompt.

waitForFileChooser(options)

此方法通常与触发文件选择的操作结合使用。

🌐 This method is typically coupled with an action that triggers file choosing.

caution

在启动文件选择器之前必须调用此方法。它不会返回当前活动的文件选择器。

🌐 This must be called before the file chooser is launched. It will not return a currently active file chooser.

caution

目前不支持拦截通过 DOM API(例如 window.showOpenFilePicker)触发的文件对话框。

🌐 Interception of file dialogs triggered via DOM APIs such as window.showOpenFilePicker is currently not supported.

附注

在“有界面”浏览器中,该方法会为用户弹出原生文件选择对话框 not showing up

🌐 In the "headful" browser, this method results in the native file picker dialog not showing up for the user.

waitForFrame(urlOrPredicate, options)

等待匹配给定条件的帧出现。

🌐 Waits for a frame matching the given conditions to appear.

waitForFunction(pageFunction, options, args)

等待提供的函数 pageFunction 在页面上下文中求值时返回一个真值。

🌐 Waits for the provided function, pageFunction, to return a truthy value when evaluated in the page's context.

waitForNavigation(options)

等待页面导航到新的 URL 或重新加载。当你运行会间接导致页面导航的代码时,它很有用。

🌐 Waits for the page to navigate to a new URL or to reload. It is useful when you run code that will indirectly cause the page to navigate.

附注

使用 History API 更改 URL 被视为一次导航。

🌐 Usage of the History API to change the URL is considered a navigation.

waitForNetworkIdle(options)

等待网络空闲。

🌐 Waits for the network to be idle.

附注

该函数将始终至少等待设定的 IdleTime

🌐 The function will always wait at least the set IdleTime.

waitForRequest(urlOrPredicate, options)

附注

可选的等待参数有:

🌐 Optional Waiting Parameters have:

  • timeout:最大等待时间,以毫秒为单位,默认值为 30 秒,传入 0 可禁用超时。可以使用 Page.setDefaultTimeout() 方法更改默认值。
  • signal:一个信号对象,允许你取消 waitForRequest 调用。
waitForResponse(urlOrPredicate, options)

附注

可选参数有:

🌐 Optional Parameter have:

  • timeout:最大等待时间,以毫秒为单位,默认值为 30 秒,传入 0 可禁用超时。可以使用 Page.setDefaultTimeout() 方法更改默认值。
  • signal:一个信号对象,允许你取消 waitForResponse 调用。
waitForSelector(selector, options)

等待页面中出现 selector。如果在调用该方法时 selector 已经存在,该方法将立即返回。如果在等待 timeout 毫秒后 selector 仍未出现,该函数将抛出异常。

🌐 Wait for the selector to appear in page. If at the moment of calling the method the selector already exists, the method will return immediately. If the selector doesn't appear after the timeout milliseconds of waiting, the function will throw.

附注

参数 options 中的可选参数有:

🌐 The optional Parameter in Arguments options are:

  • visible:布尔值等待元素出现在 DOM 中并且可见,即不具有 display: nonevisibility: hidden CSS 属性。默认值为 false
  • hidden:等待元素在 DOM 中找不到或被隐藏,即具有 display: nonevisibility: hidden CSS 属性。默认值为 false
  • timeout:等待的最长时间(以毫秒为单位)。默认为 30000(30 秒)。传入 0 可禁用超时。默认值可以通过使用 Page.setDefaultTimeout() 方法更改。
  • signal:一个信号对象,允许你取消 waitForSelector 调用。
windowId()

(实验性) 返回页面的窗口 ID。

workers()

与该页面相关的所有专用 WebWorkers

🌐 All of the dedicated WebWorkers associated with the page.

附注

这不包含 ServiceWorkers

🌐 This does not contain ServiceWorkers