Skip to main content

页面

Page 提供了与 浏览器 中的单个选项卡或 Chromium 中的 扩展背景页 进行交互的方法。一个 浏览器 实例可能有多个 页面 实例。

Page provides methods to interact with a single tab in a Browser, or an extension background page in Chromium. One Browser instance might have multiple Page instances.

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

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

const { webkit } = require('playwright');  // Or 'chromium' or 'firefox'.

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

Page 类触发各种事件(如下所述),可以使用任何 Node 的原生 EventEmitter 方法(例如 ononceremoveListener)来处理这些事件。

The Page class emits various events (described below) which can be handled using any of Node's native EventEmitter methods, such as on, once or removeListener.

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

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

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

要取消订阅事件,请使用 removeListener 方法:

To unsubscribe from events use the removeListener method:

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

方法

Methods

addInitScript

Added in: v1.8 page.addInitScript

添加将在以下场景之一进行评估的脚本:

Adds a script which would be evaluated in one of the following scenarios:

  • 每当导航页面时。

    Whenever the page is navigated.

  • 每当附加或导航子框架时。在这种情况下,脚本将在新附加的框架的上下文中进行评估。

    Whenever the child frame is attached or navigated. In this case, the script is evaluated in the context of the newly attached frame.

该脚本在创建文档之后但在运行其任何脚本之前进行评估。这对于修改 JavaScript 环境很有用,例如 种子 Math.random

The script is evaluated 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.

用法

Usage

在页面加载之前覆盖 Math.random 的示例:

An example of overriding Math.random before the page loads:

// preload.js
Math.random = () => 42;
// In your playwright script, assuming the preload.js file is in same directory
await page.addInitScript({ path: './preload.js' });
await page.addInitScript(mock => {
window.mock = mock;
}, mock);
注意

通过 browserContext.addInitScript()page.addInitScript() 安装的多个脚本的评估顺序未定义。

The order of evaluation of multiple scripts installed via browserContext.addInitScript() and page.addInitScript() is not defined.

参数

Arguments

JavaScript 文件的路径。如果 path 是相对路径,则相对于当前工作目录进行解析。可选的。

Path to the JavaScript file. If path is a relative path, then it is resolved relative to the current working directory. Optional.

原始脚本内容。可选的。

Raw script content. Optional.

要在页面中评估的脚本。

Script to be evaluated in the page.

传递给 script 的可选参数(仅在传递函数时受支持)。

Optional argument to pass to script (only supported when passing a function).


addScriptTag

Added in: v1.8 page.addScriptTag

<script> 标记添加到具有所需 url 或内容的页面中。当脚本的 onload 触发或脚本内容注入框架时返回添加的标签。

Adds a <script> tag into the page with the desired url or content. Returns the added tag when the script's onload fires or when the script content was injected into frame.

用法

Usage

await page.addScriptTag();
await page.addScriptTag(options);

参数

Arguments

要注入到框架中的原始 JavaScript 内容。

Raw JavaScript content to be injected into frame.

要注入框架的 JavaScript 文件的路径。如果 path 是相对路径,则相对于当前工作目录进行解析。

Path to the JavaScript file to be injected into frame. If path is a relative path, then it is resolved relative to the current working directory.

脚本类型。使用 'module' 来加载 Javascript ES6 模块。详细信息请参见 script

Script type. Use 'module' in order to load a Javascript ES6 module. See script for more details.

要添加的脚本的 URL。

URL of a script to be added.

返回

Returns


addStyleTag

Added in: v1.8 page.addStyleTag

<link rel="stylesheet"> 标记添加到具有所需 url 的页面中,或将 <style type="text/css"> 标记添加到内容中。当样式表的 onload 触发或 CSS 内容注入框架时返回添加的标签。

Adds a <link rel="stylesheet"> tag into the page with the desired url or a <style type="text/css"> tag with the content. Returns the added tag when the stylesheet's onload fires or when the CSS content was injected into frame.

用法

Usage

await page.addStyleTag();
await page.addStyleTag(options);

参数

Arguments

要注入到框架中的原始 CSS 内容。

Raw CSS content to be injected into frame.

要注入框架的 CSS 文件的路径。如果 path 是相对路径,则相对于当前工作目录进行解析。

Path to the CSS file to be injected into frame. If path is a relative path, then it is resolved relative to the current working directory.

<link> 标签的 URL。

URL of the <link> tag.

返回

Returns


bringToFront

Added in: v1.8 page.bringToFront

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

Brings page to front (activates tab).

用法

Usage

await page.bringToFront();

close

Added in: v1.8 page.close

如果 runBeforeUnloadfalse,则不运行任何卸载处理程序并等待页面关闭。如果 runBeforeUnloadtrue,该方法将运行卸载处理程序,但不会等待页面关闭。

If runBeforeUnload is false, does not run any unload handlers and waits for the page to be closed. If runBeforeUnload is true the method will run unload handlers, but will not wait for the page to close.

默认情况下,page.close() 不运行 beforeunload 处理程序。

By default, page.close() does not run beforeunload handlers.

注意

如果 runBeforeUnload 作为 true 传递,则可能会调用 beforeunload 对话框,并且应通过 page.on('dialog') 事件手动处理。

if runBeforeUnload is passed as true, a beforeunload dialog might be summoned and should be handled manually via page.on('dialog') event.

用法

Usage

await page.close();
await page.close(options);

参数

Arguments

  • options Object (optional)

    • reason string (optional) Added in: v1.40#

报告因页面关闭而中断的操作的原因。

The reason to be reported to the operations interrupted by the page closure.

默认为 false。是否运行 卸载前 页面处理程序。

Defaults to false. Whether to run the before unload page handlers.


content

Added in: v1.8 page.content

获取页面的完整 HTML 内容,包括文档类型。

Gets the full HTML contents of the page, including the doctype.

用法

Usage

await page.content();

返回

Returns


context

Added in: v1.8 page.context

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

Get the browser context that the page belongs to.

用法

Usage

page.context();

返回

Returns


dragAndDrop

Added in: v1.13 page.dragAndDrop

此方法将源元素拖动到目标元素。它将首先移动到源元素,执行 mousedown,然后移动到目标元素并执行 mouseup

This method drags the source element to the target element. It will first move to the source element, perform a mousedown, then move to the target element and perform a mouseup.

用法

Usage

await page.dragAndDrop('#source', '#target');
// or specify exact positions relative to the top-left corners of the elements:
await page.dragAndDrop('#source', '#target', {
sourcePosition: { x: 34, y: 7 },
targetPosition: { x: 10, y: 20 },
});

参数

Arguments

用于搜索要拖动的元素的选择器。如果有多个元素满足选择器,则将使用第一个元素。

A selector to search for an element to drag. If there are multiple elements satisfying the selector, the first will be used.

用于搜索要放置到的元素的选择器。如果有多个元素满足选择器,则将使用第一个元素。

A selector to search for an element to drop onto. If there are multiple elements satisfying the selector, the first will be used.

是否绕过 actionability 检查。默认为 false

Whether to bypass the actionability checks. Defaults to false.

启动导航的操作正在等待这些导航发生并开始加载页面。你可以通过设置此标志来选择不等待。仅在特殊情况下才需要此选项,例如导航到无法访问的页面。默认为 false

Actions that initiate navigations are waiting for these navigations to happen and for pages to start loading. You can opt out of waiting via setting this flag. You would only need this option in the exceptional cases such as navigating to inaccessible pages. Defaults to false.

此时相对于元素内边距框的左上角单击源元素。如果未指定,则使用元素的某些可见点。

Clicks on the source element at this point relative to the top-left corner of the element's padding box. If not specified, some visible point of the element is used.

  • strict boolean (optional) Added in: v1.14#

如果为 true,则调用需要选择器解析为单个元素。如果给定的选择器解析为多个元素,则调用会引发异常。

When true, the call requires selector to resolve to a single element. If given selector resolves to more than one element, the call throws an exception.

此时相对于元素内边距框的左上角放置在目标元素上。如果未指定,则使用元素的某些可见点。

Drops on the target element at this point relative to the top-left corner of the element's padding box. If not specified, some visible point of the element is used.

最长时间(以毫秒为单位)。默认为 0 - 没有超时。可以通过配置中的 actionTimeout 选项或使用 browserContext.setDefaultTimeout()page.setDefaultTimeout() 方法更改默认值。

Maximum time in milliseconds. Defaults to 0 - no timeout. The default value can be changed via actionTimeout option in the config, or by using the browserContext.setDefaultTimeout() or page.setDefaultTimeout() methods.

设置后,此方法仅执行 actionability 检查并跳过该操作。默认为 false。等待元素准备好执行操作而不执行该操作很有用。

When set, this method only performs the actionability checks and skips the action. Defaults to false. Useful to wait until the element is ready for the action without performing it.


emulateMedia

Added in: v1.8 page.emulateMedia

此方法通过 media 参数更改 CSS media type,和/或使用 colorScheme 参数更改 'prefers-colors-scheme' 媒体功能。

This method changes the CSS media type through the media argument, and/or the 'prefers-colors-scheme' media feature, using the colorScheme argument.

用法

Usage

await page.evaluate(() => matchMedia('screen').matches);
// → true
await page.evaluate(() => matchMedia('print').matches);
// → false

await page.emulateMedia({ media: 'print' });
await page.evaluate(() => matchMedia('screen').matches);
// → false
await page.evaluate(() => matchMedia('print').matches);
// → true

await page.emulateMedia({});
await page.evaluate(() => matchMedia('screen').matches);
// → true
await page.evaluate(() => matchMedia('print').matches);
// → false
await page.emulateMedia({ colorScheme: 'dark' });
await page.evaluate(() => matchMedia('(prefers-color-scheme: dark)').matches);
// → true
await page.evaluate(() => matchMedia('(prefers-color-scheme: light)').matches);
// → false
await page.evaluate(() => matchMedia('(prefers-color-scheme: no-preference)').matches);
// → false

参数

Arguments

  • options Object (optional)

    • colorScheme null|"light"|"dark"|"no-preference" (optional) Added in: v1.9#

模拟 'prefers-colors-scheme' 媒体功能,支持的值为 'light''dark''no-preference'。通过 null 将禁用配色方案模拟。

Emulates 'prefers-colors-scheme' media feature, supported values are 'light', 'dark', 'no-preference'. Passing null disables color scheme emulation.

  • forcedColors null|"active"|"none" (optional) Added in: v1.15#

模拟 'forced-colors' 媒体功能,支持的值为 'active''none'。通过 null 将禁用强制颜色模拟。

Emulates 'forced-colors' media feature, supported values are 'active' and 'none'. Passing null disables forced colors emulation.

  • media null|"screen"|"print" (optional) Added in: v1.9#

更改页面的 CSS 媒体类型。唯一允许的值为 'screen''print'null。传递 null 将禁用 CSS 媒体模拟。

Changes the CSS media type of the page. The only allowed values are 'screen', 'print' and null. Passing null disables CSS media emulation.

  • reducedMotion null|"reduce"|"no-preference" (optional) Added in: v1.12#

模拟 'prefers-reduced-motion' 媒体功能,支持的值为 'reduce''no-preference'。通过 null 将禁用简化运动模拟。

Emulates 'prefers-reduced-motion' media feature, supported values are 'reduce', 'no-preference'. Passing null disables reduced motion emulation.


evaluate

Added in: v1.8 page.evaluate

返回 pageFunction 调用的值。

Returns the value of the pageFunction invocation.

如果传递给 page.evaluate() 的函数返回 Promise,那么 page.evaluate() 将等待 Promise 解析并返回其值。

If the function passed to the page.evaluate() returns a Promise, then page.evaluate() would wait for the promise to resolve and return its value.

如果传递给 page.evaluate() 的函数返回非 可串行化 值,则 page.evaluate() 解析为 undefined。Playwright 还支持传输一些 JSON 无法序列化的附加值:-0NaNInfinity-Infinity

If the function passed to the page.evaluate() returns a non-Serializable value, then page.evaluate() resolves to undefined. Playwright also supports transferring some additional values that are not serializable by JSON: -0, NaN, Infinity, -Infinity.

用法

Usage

将参数传递给 pageFunction

Passing argument to pageFunction:

const result = await page.evaluate(([x, y]) => {
return Promise.resolve(x * y);
}, [7, 8]);
console.log(result); // prints "56"

也可以传入字符串而不是函数:

A string can also be passed in instead of a function:

console.log(await page.evaluate('1 + 2')); // prints "3"
const x = 10;
console.log(await page.evaluate(`1 + ${x}`)); // prints "11"

ElementHandle 实例可以作为参数传递给 page.evaluate()

ElementHandle instances can be passed as an argument to the page.evaluate():

const bodyHandle = await page.evaluate('document.body');
const html = await page.evaluate<string, HTMLElement>(([body, suffix]) =>
body.innerHTML + suffix, [bodyHandle, 'hello']
);
await bodyHandle.dispose();

参数

Arguments

要在页面上下文中评估的函数。

Function to be evaluated in the page context.

传递给 pageFunction 的可选参数。

Optional argument to pass to pageFunction.

返回

Returns


evaluateHandle

Added in: v1.8 page.evaluateHandle

pageFunction 调用的值返回为 JSHandle

Returns the value of the pageFunction invocation as a JSHandle.

page.evaluate()page.evaluateHandle() 之间的唯一区别是 page.evaluateHandle() 返回 JSHandle

The only difference between page.evaluate() and page.evaluateHandle() is that page.evaluateHandle() returns JSHandle.

如果传递给 page.evaluateHandle() 的函数返回 Promise,那么 page.evaluateHandle() 将等待 Promise 解析并返回其值。

If the function passed to the page.evaluateHandle() returns a Promise, then page.evaluateHandle() would wait for the promise to resolve and return its value.

用法

Usage

// Handle for the window object.
const aWindowHandle = await page.evaluateHandle(() => Promise.resolve(window));

也可以传入字符串而不是函数:

A string can also be passed in instead of a function:

const aHandle = await page.evaluateHandle('document'); // Handle for the 'document'

JSHandle 实例可以作为参数传递给 page.evaluateHandle()

JSHandle instances can be passed as an argument to the page.evaluateHandle():

const aHandle = await page.evaluateHandle(() => document.body);
const resultHandle = await page.evaluateHandle(body => body.innerHTML, aHandle);
console.log(await resultHandle.jsonValue());
await resultHandle.dispose();

参数

Arguments

要在页面上下文中评估的函数。

Function to be evaluated in the page context.

传递给 pageFunction 的可选参数。

Optional argument to pass to pageFunction.

返回

Returns


exposeBinding

Added in: v1.8 page.exposeBinding

该方法在此页面中每个帧的 window 对象上添加一个名为 name 的函数。调用时,该函数执行 callback 并返回 Promise,该 Promise 解析为 callback 的返回值。如果 callback 返回 Promise,则将等待它。

The method adds a function called name on the window object of every frame in this page. When called, the function executes callback and returns a Promise which resolves to the return value of callback. If the callback returns a Promise, it will be awaited.

callback 函数的第一个参数包含有关调用者的信息:{ browserContext: BrowserContext, page: Page, frame: Frame }

The first argument of the callback function contains information about the caller: { browserContext: BrowserContext, page: Page, frame: Frame }.

请参阅 browserContext.exposeBinding() 了解上下文范围的版本。

See browserContext.exposeBinding() for the context-wide version.

注意

通过 page.exposeBinding() 安装的功能在导航中仍然存在。

Functions installed via page.exposeBinding() survive navigations.

用法

Usage

向页面中的所有框架公开页面 URL 的示例:

An example of exposing page URL to all frames in a page:

const { webkit } = require('playwright');  // Or 'chromium' or 'firefox'.

(async () => {
const browser = await webkit.launch({ headless: false });
const context = await browser.newContext();
const page = await context.newPage();
await page.exposeBinding('pageURL', ({ page }) => page.url());
await page.setContent(`
<script>
async function onClick() {
document.querySelector('div').textContent = await window.pageURL();
}
</script>
<button onclick="onClick()">Click me</button>
<div></div>
`);
await page.click('button');
})();

传递元素句柄的示例:

An example of passing an element handle:

await page.exposeBinding('clicked', async (source, element) => {
console.log(await element.textContent());
}, { handle: true });
await page.setContent(`
<script>
document.addEventListener('click', event => window.clicked(event.target));
</script>
<div>Click me</div>
<div>Or click me</div>
`);

参数

Arguments

窗口对象上的函数名称。

Name of the function on the window object.

将在 Playwright 上下文中调用的回调函数。

Callback function that will be called in the Playwright's context.

是否将参数作为句柄传递,而不是按值传递。传递句柄时,仅支持一个参数。按值传递时,支持多个参数。

Whether to pass the argument as a handle, instead of passing by value. When passing a handle, only one argument is supported. When passing by value, multiple arguments are supported.


exposeFunction

Added in: v1.8 page.exposeFunction

该方法在页面中每个帧的 window 对象上添加一个名为 name 的函数。调用时,该函数执行 callback 并返回 Promise,该 Promise 解析为 callback 的返回值。

The method adds a function called name on the window object of every frame in the page. When called, the function executes callback and returns a Promise which resolves to the return value of callback.

如果 callback 返回 Promise,则将等待它。

If the callback returns a Promise, it will be awaited.

请参阅 browserContext.exposeFunction() 了解上下文范围内的公开函数。

See browserContext.exposeFunction() for context-wide exposed function.

注意

通过 page.exposeFunction() 安装的功能在导航中仍然存在。

Functions installed via page.exposeFunction() survive navigations.

用法

Usage

向页面添加 sha256 功能的示例:

An example of adding a sha256 function to the page:

const { webkit } = require('playwright');  // Or 'chromium' or 'firefox'.
const crypto = require('crypto');

(async () => {
const browser = await webkit.launch({ headless: false });
const page = await browser.newPage();
await page.exposeFunction('sha256', text =>
crypto.createHash('sha256').update(text).digest('hex'),
);
await page.setContent(`
<script>
async function onClick() {
document.querySelector('div').textContent = await window.sha256('PLAYWRIGHT');
}
</script>
<button onclick="onClick()">Click me</button>
<div></div>
`);
await page.click('button');
})();

参数

Arguments

窗口对象上的函数名称

Name of the function on the window object

将在 Playwright 上下文中调用的回调函数。

Callback function which will be called in Playwright's context.


frame

Added in: v1.8 page.frame

返回与指定条件匹配的帧。必须指定 nameurl

Returns frame matching the specified criteria. Either name or url must be specified.

用法

Usage

const frame = page.frame('frame-name');
const frame = page.frame({ url: /.*domain.*/ });

参数

Arguments

iframename 属性中指定的帧名称。可选的。

Frame name specified in the iframe's name attribute. Optional.

通配符模式、正则表达式模式或谓词接收帧的 url 作为 URL 对象。可选的。

A glob pattern, regex pattern or predicate receiving frame's url as a URL object. Optional.

帧名称或其他帧查找选项。

Frame name or other frame lookup options.

返回

Returns


frameLocator

Added in: v1.17 page.frameLocator

使用 iframe 时,你可以创建一个框架定位器,该定位器将进入 iframe 并允许选择该 iframe 中的元素。

When working with iframes, you can create a frame locator that will enter the iframe and allow selecting elements in that iframe.

用法

Usage

以下代码片段在 ID 为 my-frame 的 iframe 中定位带有文本 "提交" 的元素,例如 <iframe id="my-frame">

Following snippet locates element with text "Submit" in the iframe with id my-frame, like <iframe id="my-frame">:

const locator = page.frameLocator('#my-iframe').getByText('Submit');
await locator.click();

参数

Arguments

解析 DOM 元素时使用的选择器。

A selector to use when resolving DOM element.

返回

Returns


frames

Added in: v1.8 page.frames

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

An array of all frames attached to the page.

用法

Usage

page.frames();

返回

Returns


getByAltText

Added in: v1.27 page.getByAltText

允许通过替代文本定位元素。

Allows locating elements by their alt text.

用法

Usage

例如,此方法将通过替代文本 "Playwright 标志" 查找图片:

For example, this method will find the image by alt text "Playwright logo":

<img alt='Playwright logo'>
await page.getByAltText('Playwright logo').click();

参数

Arguments

用于定位元素的文本。

Text to locate the element for.

是否查找精确匹配:区分大小写和整个字符串。默认为 false。通过正则表达式定位时被忽略。请注意,完全匹配仍然会修剪空格。

Whether to find an exact match: case-sensitive and whole-string. Default to false. Ignored when locating by a regular expression. Note that exact match still trims whitespace.

返回

Returns


getByLabel

Added in: v1.27 page.getByLabel

允许通过关联的 <label>aria-labelledby 元素的文本或通过 aria-label 属性来定位输入元素。

Allows locating input elements by the text of the associated <label> or aria-labelledby element, or by the aria-label attribute.

用法

Usage

例如,此方法将在以下 DOM 中查找标签 "用户名" 和 "密码" 的输入:

For example, this method will find inputs by label "Username" and "Password" in the following DOM:

<input aria-label="Username">
<label for="password-input">Password:</label>
<input id="password-input">
await page.getByLabel('Username').fill('john');
await page.getByLabel('Password').fill('secret');

参数

Arguments

用于定位元素的文本。

Text to locate the element for.

是否查找精确匹配:区分大小写和整个字符串。默认为 false。通过正则表达式定位时被忽略。请注意,完全匹配仍然会修剪空格。

Whether to find an exact match: case-sensitive and whole-string. Default to false. Ignored when locating by a regular expression. Note that exact match still trims whitespace.

返回

Returns


getByPlaceholder

Added in: v1.27 page.getByPlaceholder

允许通过占位符文本定位输入元素。

Allows locating input elements by the placeholder text.

用法

Usage

例如,考虑以下 DOM 结构。

For example, consider the following DOM structure.

<input type="email" placeholder="name@example.com" />

你可以在通过占位符文本找到输入后填充输入:

You can fill the input after locating it by the placeholder text:

await page
.getByPlaceholder('name@example.com')
.fill('playwright@microsoft.com');

参数

Arguments

用于定位元素的文本。

Text to locate the element for.

是否查找精确匹配:区分大小写和整个字符串。默认为 false。通过正则表达式定位时被忽略。请注意,完全匹配仍然会修剪空格。

Whether to find an exact match: case-sensitive and whole-string. Default to false. Ignored when locating by a regular expression. Note that exact match still trims whitespace.

返回

Returns


getByRole

Added in: v1.27 page.getByRole

允许通过 ARIA 角色ARIA 属性可访问的名称 定位元素。

Allows locating elements by their ARIA role, ARIA attributes and accessible name.

用法

Usage

考虑以下 DOM 结构。

Consider the following DOM structure.

<h3>Sign up</h3>
<label>
<input type="checkbox" /> Subscribe
</label>
<br/>
<button>Submit</button>

你可以通过每个元素的隐式角色来定位它:

You can locate each element by it's implicit role:

await expect(page.getByRole('heading', { name: 'Sign up' })).toBeVisible();

await page.getByRole('checkbox', { name: 'Subscribe' }).check();

await page.getByRole('button', { name: /submit/i }).click();

参数

Arguments

  • role "alert"|"alertdialog"|"application"|"article"|"banner"|"blockquote"|"button"|"caption"|"cell"|"checkbox"|"code"|"columnheader"|"combobox"|"complementary"|"contentinfo"|"definition"|"deletion"|"dialog"|"directory"|"document"|"emphasis"|"feed"|"figure"|"form"|"generic"|"grid"|"gridcell"|"group"|"heading"|"img"|"insertion"|"link"|"list"|"listbox"|"listitem"|"log"|"main"|"marquee"|"math"|"meter"|"menu"|"menubar"|"menuitem"|"menuitemcheckbox"|"menuitemradio"|"navigation"|"none"|"note"|"option"|"paragraph"|"presentation"|"progressbar"|"radio"|"radiogroup"|"region"|"row"|"rowgroup"|"rowheader"|"scrollbar"|"search"|"searchbox"|"separator"|"slider"|"spinbutton"|"status"|"strong"|"subscript"|"superscript"|"switch"|"tab"|"table"|"tablist"|"tabpanel"|"term"|"textbox"|"time"|"timer"|"toolbar"|"tooltip"|"tree"|"treegrid"|"treeitem"#

    所需的咏叹调角色。

    Required aria role.

通常由 aria-checked 或原生 <input type=checkbox> 控件设置的属性。

An attribute that is usually set by aria-checked or native <input type=checkbox> controls.

了解有关 aria-checked 的更多信息。

Learn more about aria-checked.

通常由 aria-disableddisabled 设置的属性。

An attribute that is usually set by aria-disabled or disabled.

note

disabled is inherited through the DOM hierarchy. Learn more about aria-disabled. :::与大多数其他属性不同,

  • exact boolean (optional) Added in: v1.28#

name 是否完全匹配:区分大小写和整个字符串。默认为 false。当 name 是正则表达式时被忽略。请注意,完全匹配仍然会修剪空格。

Whether name is matched exactly: case-sensitive and whole-string. Defaults to false. Ignored when name is a regular expression. Note that exact match still trims whitespace.

通常由 aria-expanded 设置的属性。

An attribute that is usually set by aria-expanded.

了解有关 aria-expanded 的更多信息。

Learn more about aria-expanded.

控制隐藏元素是否匹配的选项。默认情况下,角色选择器仅匹配非隐藏元素(如 由 ARIA 定义)。

Option that controls whether hidden elements are matched. By default, only non-hidden elements, as defined by ARIA, are matched by role selector.

了解有关 aria-hidden 的更多信息。

Learn more about aria-hidden.

通常为角色 headinglistitemrowtreeitem 提供的数字属性,并为 <h1>-<h6> 元素提供默认值。

A number attribute that is usually present for roles heading, listitem, row, treeitem, with default values for <h1>-<h6> elements.

了解有关 aria-level 的更多信息。

Learn more about aria-level.

可访问的名称 匹配的选项。默认情况下,匹配不区分大小写并搜索子字符串,使用 exact 来控制此行为。

Option to match the accessible name. By default, matching is case-insensitive and searches for a substring, use exact to control this behavior.

了解有关 可访问的名称 的更多信息。

Learn more about accessible name.

通常由 aria-pressed 设置的属性。

An attribute that is usually set by aria-pressed.

了解有关 aria-pressed 的更多信息。

Learn more about aria-pressed.

通常由 aria-selected 设置的属性。

An attribute that is usually set by aria-selected.

了解有关 aria-selected 的更多信息。

Learn more about aria-selected.

返回

Returns

细节

Details

角色选择器不会取代可访问性审核和一致性测试,而是提供有关 ARIA 指南的早期反馈。

Role selector does not replace accessibility audits and conformance tests, but rather gives early feedback about the ARIA guidelines.

许多 html 元素都有一个隐式的 明确的角色,可以被角色选择器识别。你可以找到所有的 此处支持的角色。ARIA 指南不建议通过将 role 和/或 aria-* 属性设置为默认值来复制隐式角色和属性。

Many html elements have an implicitly defined role that is recognized by the role selector. You can find all the supported roles here. ARIA guidelines do not recommend duplicating implicit roles and attributes by setting role and/or aria-* attributes to default values.


getByTestId

Added in: v1.27page.getByTestId

通过测试 ID 定位元素。

Locate element by the test id.

用法

Usage

考虑以下 DOM 结构。

Consider the following DOM structure.

<button data-testid="directions">Itinéraire</button>

你可以通过元素的测试 ID 来定位该元素:

You can locate the element by it's test id:

await page.getByTestId('directions').click();

参数

Arguments

用于定位元素的 ID。

Id to locate the element by.

返回

Returns

细节

Details

默认情况下,data-testid 属性用作测试 ID。如有必要,请使用 selectors.setTestIdAttribute() 配置不同的测试 ID 属性。

By default, the data-testid attribute is used as a test id. Use selectors.setTestIdAttribute() to configure a different test id attribute if necessary.

// Set custom test id attribute from @playwright/test config:
import { defineConfig } from '@playwright/test';

export default defineConfig({
use: {
testIdAttribute: 'data-pw'
},
});

getByText

Added in: v1.27page.getByText

允许定位包含给定文本的元素。

Allows locating elements that contain given text.

另请参阅 locator.filter(),它允许按其他条件(例如可访问的角色)进行匹配,然后按文本内容进行过滤。

See also locator.filter() that allows to match by another criteria, like an accessible role, and then filter by the text content.

用法

Usage

考虑以下 DOM 结构:

Consider the following DOM structure:

<div>Hello <span>world</span></div>
<div>Hello</div>

你可以通过文本子字符串、精确字符串或正则表达式进行定位:

You can locate by text substring, exact string, or a regular expression:

// Matches <span>
page.getByText('world');

// Matches first <div>
page.getByText('Hello world');

// Matches second <div>
page.getByText('Hello', { exact: true });

// Matches both <div>s
page.getByText(/Hello/);

// Matches second <div>
page.getByText(/^hello$/i);

参数

Arguments

用于定位元素的文本。

Text to locate the element for.

是否查找精确匹配:区分大小写和整个字符串。默认为 false。通过正则表达式定位时被忽略。请注意,完全匹配仍然会修剪空格。

Whether to find an exact match: case-sensitive and whole-string. Default to false. Ignored when locating by a regular expression. Note that exact match still trims whitespace.

返回

Returns

细节

Details

按文本匹配始终会标准化空格,即使是完全匹配也是如此。例如,它将多个空格变成一个,将换行符变成空格,并忽略前导和尾随空白。

Matching by text always normalizes whitespace, even with exact match. For example, it turns multiple spaces into one, turns line breaks into spaces and ignores leading and trailing whitespace.

buttonsubmit 类型的输入元素通过其 value 而不是文本内容进行匹配。例如,通过文本 "Log in" 查找匹配 <input type=button value="Log in">

Input elements of the type button and submit are matched by their value instead of the text content. For example, locating by text "Log in" matches <input type=button value="Log in">.


getByTitle

Added in: v1.27page.getByTitle

允许通过标题属性定位元素。

Allows locating elements by their title attribute.

用法

Usage

考虑以下 DOM 结构。

Consider the following DOM structure.

<span title='Issues count'>25 issues</span>

你可以通过标题文本找到问题后查看问题数:

You can check the issues count after locating it by the title text:

await expect(page.getByTitle('Issues count')).toHaveText('25 issues');

参数

Arguments

用于定位元素的文本。

Text to locate the element for.

是否查找精确匹配:区分大小写和整个字符串。默认为 false。通过正则表达式定位时被忽略。请注意,完全匹配仍然会修剪空格。

Whether to find an exact match: case-sensitive and whole-string. Default to false. Ignored when locating by a regular expression. Note that exact match still trims whitespace.

返回

Returns


goBack

Added in: v1.8page.goBack

返回主要资源响应。如果存在多个重定向,导航将使用最后一个重定向的响应进行解析。如果无法返回,则返回 null

Returns the main resource response. In case of multiple redirects, the navigation will resolve with the response of the last redirect. If can not go back, returns null.

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

Navigate to the previous page in history.

用法

Usage

await page.goBack();
await page.goBack(options);

参数

Arguments

最大操作时间(以毫秒为单位)。默认为 0 - 没有超时。可以通过配置中的 navigationTimeout 选项或使用 browserContext.setDefaultNavigationTimeout()browserContext.setDefaultTimeout()page.setDefaultNavigationTimeout()page.setDefaultTimeout() 方法更改默认值。

Maximum operation time in milliseconds. Defaults to 0 - no timeout. The default value can be changed via navigationTimeout option in the config, or by using the browserContext.setDefaultNavigationTimeout(), browserContext.setDefaultTimeout(), page.setDefaultNavigationTimeout() or page.setDefaultTimeout() methods.

  • waitUntil "load"|"domcontentloaded"|"networkidle"|"commit"(可选)#

    waitUntil "load"|"domcontentloaded"|"networkidle"|"commit" (optional)#

    什么时候才认为操作成功,默认为 load。事件可以是:

    When to consider operation succeeded, defaults to load. Events can be either:

    • 'domcontentloaded' - 认为操作在 DOMContentLoaded 事件触发时完成。

      'domcontentloaded' - consider operation to be finished when the DOMContentLoaded event is fired.

    • 'load' - 认为操作在 load 事件触发时完成。

      'load' - consider operation to be finished when the load event is fired.

    • 'networkidle' - 不鼓励在至少 500 毫秒内没有网络连接时考虑操作完成。不要使用此方法进行测试,而是依靠网络断言来评估准备情况。

      'networkidle' - DISCOURAGED consider operation to be finished when there are no network connections for at least 500 ms. Don't use this method for testing, rely on web assertions to assess readiness instead.

    • 'commit' - 当收到网络响应并且文档开始加载时,认为操作完成。

      'commit' - consider operation to be finished when network response is received and the document started loading.

返回

Returns


goForward

Added in: v1.8page.goForward

返回主要资源响应。如果存在多个重定向,导航将使用最后一个重定向的响应进行解析。如果不能前进,则返回 null

Returns the main resource response. In case of multiple redirects, the navigation will resolve with the response of the last redirect. If can not go forward, returns null.

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

Navigate to the next page in history.

用法

Usage

await page.goForward();
await page.goForward(options);

参数

Arguments

最大操作时间(以毫秒为单位)。默认为 0 - 没有超时。可以通过配置中的 navigationTimeout 选项或使用 browserContext.setDefaultNavigationTimeout()browserContext.setDefaultTimeout()page.setDefaultNavigationTimeout()page.setDefaultTimeout() 方法更改默认值。

Maximum operation time in milliseconds. Defaults to 0 - no timeout. The default value can be changed via navigationTimeout option in the config, or by using the browserContext.setDefaultNavigationTimeout(), browserContext.setDefaultTimeout(), page.setDefaultNavigationTimeout() or page.setDefaultTimeout() methods.

  • waitUntil "load"|"domcontentloaded"|"networkidle"|"commit"(可选)#

    waitUntil "load"|"domcontentloaded"|"networkidle"|"commit" (optional)#

    什么时候才认为操作成功,默认为 load。事件可以是:

    When to consider operation succeeded, defaults to load. Events can be either:

    • 'domcontentloaded' - 认为操作在 DOMContentLoaded 事件触发时完成。

      'domcontentloaded' - consider operation to be finished when the DOMContentLoaded event is fired.

    • 'load' - 认为操作在 load 事件触发时完成。

      'load' - consider operation to be finished when the load event is fired.

    • 'networkidle' - 不鼓励在至少 500 毫秒内没有网络连接时考虑操作完成。不要使用此方法进行测试,而是依靠网络断言来评估准备情况。

      'networkidle' - DISCOURAGED consider operation to be finished when there are no network connections for at least 500 ms. Don't use this method for testing, rely on web assertions to assess readiness instead.

    • 'commit' - 当收到网络响应并且文档开始加载时,认为操作完成。

      'commit' - consider operation to be finished when network response is received and the document started loading.

返回

Returns


goto

Added in: v1.8page.goto

返回主要资源响应。如果存在多个重定向,导航将使用第一个非重定向响应进行解析。

Returns the main resource response. In case of multiple redirects, the navigation will resolve with the first non-redirect response.

如果出现以下情况,该方法将抛出错误:

The method will throw an error if:

  • 存在 SSL 错误(例如,在自签名证书的情况下)。

    there's an SSL error (e.g. in case of self-signed certificates).

  • 目标网址无效。

    target URL is invalid.

  • 导航期间超出 timeout

    the timeout is exceeded during navigation.

  • 远程服务器没有响应或无法访问。

    the remote server does not respond or is unreachable.

  • 主要资源加载失败。

    the main resource failed to load.

当远程服务器返回任何有效的 HTTP 状态代码(包括 404 "未找到" 和 500 "内部服务器错误")时,该方法不会抛出错误。此类响应的状态代码可以通过调用 response.status() 来检索。

The 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 response.status().

注意

该方法要么抛出错误,要么返回主资源响应。唯一的例外是导航到 about:blank 或导航到具有不同哈希的同一 URL,这将成功并返回 null

The method either throws an error or returns a main resource response. The only exceptions are navigation to about:blank or navigation to the same URL with a different hash, which would succeed and return null.

注意

无头模式不支持导航至 PDF 文档。参见 上游问题

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

用法

Usage

await page.goto(url);
await page.goto(url, options);

参数

Arguments

页面导航到的 URL。url 应包含方案,例如 https://。当通过上下文选项提供 baseURL 并且传递的 URL 是路径时,它将通过 new URL() 构造函数合并。

URL to navigate page to. The url should include scheme, e.g. https://. When a baseURL via the context options was provided and the passed URL is a path, it gets merged via the new URL() constructor.

Referer 标头值。如果提供,它将优先于 page.setExtraHTTPHeaders() 设置的 Referer 标头值。

Referer header value. If provided it will take preference over the referer header value set by page.setExtraHTTPHeaders().

最大操作时间(以毫秒为单位)。默认为 0 - 没有超时。可以通过配置中的 navigationTimeout 选项或使用 browserContext.setDefaultNavigationTimeout()browserContext.setDefaultTimeout()page.setDefaultNavigationTimeout()page.setDefaultTimeout() 方法更改默认值。

Maximum operation time in milliseconds. Defaults to 0 - no timeout. The default value can be changed via navigationTimeout option in the config, or by using the browserContext.setDefaultNavigationTimeout(), browserContext.setDefaultTimeout(), page.setDefaultNavigationTimeout() or page.setDefaultTimeout() methods.

  • waitUntil "load"|"domcontentloaded"|"networkidle"|"commit"(可选)#

    waitUntil "load"|"domcontentloaded"|"networkidle"|"commit" (optional)#

    什么时候才认为操作成功,默认为 load。事件可以是:

    When to consider operation succeeded, defaults to load. Events can be either:

    • 'domcontentloaded' - 认为操作在 DOMContentLoaded 事件触发时完成。

      'domcontentloaded' - consider operation to be finished when the DOMContentLoaded event is fired.

    • 'load' - 认为操作在 load 事件触发时完成。

      'load' - consider operation to be finished when the load event is fired.

    • 'networkidle' - 不鼓励在至少 500 毫秒内没有网络连接时考虑操作完成。不要使用此方法进行测试,而是依靠网络断言来评估准备情况。

      'networkidle' - DISCOURAGED consider operation to be finished when there are no network connections for at least 500 ms. Don't use this method for testing, rely on web assertions to assess readiness instead.

    • 'commit' - 当收到网络响应并且文档开始加载时,认为操作完成。

      'commit' - consider operation to be finished when network response is received and the document started loading.

返回

Returns


isClosed

Added in: v1.8 page.isClosed

表示该页面已关闭。

Indicates that the page has been closed.

用法

Usage

page.isClosed();

返回

Returns


locator

Added in: v1.14 page.locator

该方法返回一个元素定位器,可用于在此页面/框架上执行操作。定位器在执行操作之前立即解析为元素,因此同一定位器上的一系列操作实际上可以在不同的 DOM 元素上执行。如果这些操作之间的 DOM 结构发生了变化,就会发生这种情况。

The method returns an element locator that can be used to perform actions on this page / frame. Locator is resolved to the element immediately before performing an action, so a series of actions on the same locator can in fact be performed on different DOM elements. That would happen if the DOM structure between those actions has changed.

了解有关定位器的更多信息

Learn more about locators.

用法

Usage

page.locator(selector);
page.locator(selector, options);

参数

Arguments

解析 DOM 元素时使用的选择器。

A selector to use when resolving DOM element.

将方法的结果范围缩小到包含与此相对定位器匹配的元素的结果。例如,具有 text=Playwrightarticle<article><div>Playwright</div></article> 相匹配。

Narrows down the results of the method to those which contain elements matching this relative locator. For example, article that has text=Playwright matches <article><div>Playwright</div></article>.

内部定位器必须相对于外部定位器,并且从外部定位器匹配开始查询,而不是从文档根开始。例如,你可以在 <article><content><div>Playwright</div></content></article> 中找到 content,其中包含 div。但是,查找具有 article divcontent 将会失败,因为内部定位器必须是相对的,并且不应使用 content 之外的任何元素。

Inner locator must be relative to the outer locator and is queried starting with the outer locator match, not the document root. For example, you can find content that has div in <article><content><div>Playwright</div></content></article>. However, looking for content that has article div will fail, because the inner locator must be relative and should not use any elements outside the content.

请注意,外部和内部定位器必须属于同一框架。内部定位器不得包含 FrameLocator

Note that outer and inner locators must belong to the same frame. Inner locator must not contain FrameLocators.

  • hasNot Locator (optional) Added in: v1.33#

匹配不包含与内部定位器匹配的元素的元素。内部定位器是针对外部定位器进行查询的。例如,没有 divarticle<article><span>Playwright</span></article> 相匹配。

Matches elements that do not contain an element that matches an inner locator. Inner locator is queried against the outer one. For example, article that does not have div matches <article><span>Playwright</span></article>.

请注意,外部和内部定位器必须属于同一框架。内部定位器不得包含 FrameLocator

Note that outer and inner locators must belong to the same frame. Inner locator must not contain FrameLocators.

匹配内部某处(可能在子元素或后代元素中)不包含指定文本的元素。当传递 string 时,匹配不区分大小写并搜索子字符串。

Matches elements that do not contain specified text somewhere inside, possibly in a child or a descendant element. When passed a string, matching is case-insensitive and searches for a substring.

匹配内部某处(可能在子元素或后代元素中)包含指定文本的元素。当传递 string 时,匹配不区分大小写并搜索子字符串。例如,"Playwright" 匹配 <article><div>Playwright</div></article>

Matches elements containing specified text somewhere inside, possibly in a child or a descendant element. When passed a string, matching is case-insensitive and searches for a substring. For example, "Playwright" matches <article><div>Playwright</div></article>.

返回

Returns


mainFrame

Added in: v1.8 page.mainFrame

页面的主框架。页面保证有一个在导航期间持续存在的主框架。

The page's main frame. Page is guaranteed to have a main frame which persists during navigations.

用法

Usage

page.mainFrame();

返回

Returns


opener

Added in: v1.8 page.opener

返回弹出页面的开场白和其他页面的 null。如果开启器已经关闭,则返回 null

Returns the opener for popup pages and null for others. If the opener has been closed already the returns null.

用法

Usage

await page.opener();

返回

Returns


pause

Added in: v1.9 page.pause

暂停脚本执行。Playwright 将停止执行脚本并等待用户按下页面叠加中的 '恢复' 按钮或在 DevTools 控制台中调用 playwright.resume()

Pauses script execution. Playwright will stop executing the script and wait for the user to either press 'Resume' button in the page overlay or to call playwright.resume() in the DevTools console.

用户可以在暂停时检查选择器或执行手动步骤。恢复将从暂停的位置继续运行原始脚本。

User can inspect selectors or perform manual steps while paused. Resume will continue running the original script from the place it was paused.

注意

此方法要求 Playwright 以引导模式启动,并在 browserType.launch() 中使用虚假的 headless 值。

This method requires Playwright to be started in a headed mode, with a falsy headless value in the browserType.launch().

用法

Usage

await page.pause();

pdf

Added in: v1.8 page.pdf

返回 PDF 缓冲区。

Returns the PDF buffer.

注意

目前仅 Chromium headless 支持生成 pdf。

Generating a pdf is currently only supported in Chromium headless.

page.pdf() 使用 print css 媒体生成页面的 pdf。要使用 screen 媒体生成 pdf,请在调用 page.pdf() 之前调用 page.emulateMedia()

page.pdf() generates a pdf of the page with print css media. To generate a pdf with screen media, call page.emulateMedia() 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.

用法

Usage

// Generates a PDF with 'screen' media type.
await page.emulateMedia({ media: 'screen' });
await page.pdf({ path: 'page.pdf' });

widthheightmargin 选项接受标有单位的值。未标记的值被视为像素。

The width, height, and margin options accept values labeled with units. Unlabeled values are treated as pixels.

举几个例子:

A few examples:

  • page.pdf({width: 100}) - 打印宽度设置为 100 像素

    page.pdf({width: 100}) - prints with width set to 100 pixels

  • page.pdf({width: '100px'}) - 打印宽度设置为 100 像素

    page.pdf({width: '100px'}) - prints with width set to 100 pixels

  • page.pdf({width: '10cm'}) - 打印宽度设置为 10 厘米。

    page.pdf({width: '10cm'}) - prints with width set to 10 centimeters.

所有可能的单位是:

All possible units are:

  • px - pixel

  • in - inch

  • cm - centimeter

  • mm - millimeter

format 选项是:

The format options are:

  • Letter:8.5 英寸 x 11 英寸

    Letter: 8.5in x 11in

  • Legal:8.5 英寸 x 14 英寸

    Legal: 8.5in x 14in

  • Tabloid:11 英寸 x 17 英寸

    Tabloid: 11in x 17in

  • Ledger:17 英寸 x 11 英寸

    Ledger: 17in x 11in

  • A0:33.1 英寸 x 46.8 英寸

    A0: 33.1in x 46.8in

  • A1:23.4 英寸 x 33.1 英寸

    A1: 23.4in x 33.1in

  • A2:16.54 英寸 x 23.4 英寸

    A2: 16.54in x 23.4in

  • A3:11.7 英寸 x 16.54 英寸

    A3: 11.7in x 16.54in

  • A4:8.27 英寸 x 11.7 英寸

    A4: 8.27in x 11.7in

  • A5:5.83 英寸 x 8.27 英寸

    A5: 5.83in x 8.27in

  • A6:4.13 英寸 x 5.83 英寸

    A6: 4.13in x 5.83in

注意

headerTemplatefooterTemplate 标记具有以下限制:1)不会评估模板内的脚本标签。2)页面样式在模板内不可见。

headerTemplate and footerTemplate markup have the following limitations: > 1. Script tags inside templates are not evaluated. > 2. Page styles are not visible inside templates.

参数

Arguments

显示页眉和页脚。默认为 false

Display header and footer. Defaults to false.

  • footerTemplate string (optional)#

打印页脚的 HTML 模板。应使用与 headerTemplate 相同的格式。

HTML template for the print footer. Should use the same format as the headerTemplate.

纸张格式。如果设置,则优先于 widthheight 选项。默认为 '信'。

Paper format. If set, takes priority over width or height options. Defaults to 'Letter'.

  • headerTemplate string (optional)#

打印标题的 HTML 模板。应该是有效的 HTML 标记,具有以下用于将打印值注入其中的类:

HTML template for the print header. Should be valid HTML markup with following classes used to inject printing values into them:

  • 'date' 格式的打印日期

    'date' formatted print date

  • 'title' 文件标题

    'title' document title

  • 'url' 文档位置

    'url' document location

  • 'pageNumber' 当前页码

    'pageNumber' current page number

  • 文档总页数 'totalPages'

    'totalPages' total pages in the document

纸张高度,接受标有单位的值。

Paper height, accepts values labeled with units.

纸张方向。默认为 false

Paper orientation. Defaults to false.

上边距,接受标有单位的值。默认为 0

Top margin, accepts values labeled with units. Defaults to 0.

右边距,接受标有单位的值。默认为 0

Right margin, accepts values labeled with units. Defaults to 0.

下边距,接受标有单位的值。默认为 0

Bottom margin, accepts values labeled with units. Defaults to 0.

左边距,接受标有单位的值。默认为 0

Left margin, accepts values labeled with units. Defaults to 0.

纸张边距,默认为无。

Paper margins, defaults to none.

要打印的纸张范围,例如 '1-5, 8, 11-13'。默认为空字符串,表示打印所有页面。

Paper ranges to print, e.g., '1-5, 8, 11-13'. Defaults to the empty string, which means print all pages.

PDF 保存到的文件路径。如果 path 是相对路径,则相对于当前工作目录进行解析。如果未提供路径,PDF 将不会保存到磁盘。

The file path to save the PDF to. If path is a relative path, then it is resolved relative to the current working directory. If no path is provided, the PDF won't be saved to the disk.

使页面中声明的任何 CSS @page 大小优先于 widthheightformat 选项中声明的大小。默认为 false,这将缩放内容以适合纸张尺寸。

Give any CSS @page size declared in the page priority over what is declared in width and height or format options. Defaults to false, which will scale the content to fit the paper size.

打印背景图形。默认为 false

Print background graphics. Defaults to false.

网页渲染的比例。默认为 1。缩放量必须介于 0.1 和 2 之间。

Scale of the webpage rendering. Defaults to 1. Scale amount must be between 0.1 and 2.

纸张宽度,接受标有单位的值。

Paper width, accepts values labeled with units.

返回

Returns


reload

Added in: v1.8 page.reload

此方法会重新加载当前页面,就像用户触发浏览器刷新一样。返回主要资源响应。如果存在多个重定向,导航将使用最后一个重定向的响应进行解析。

This method reloads the current page, in the same way as if the user had triggered a browser refresh. Returns the main resource response. In case of multiple redirects, the navigation will resolve with the response of the last redirect.

用法

Usage

await page.reload();
await page.reload(options);

参数

Arguments

最大操作时间(以毫秒为单位)。默认为 0 - 没有超时。可以通过配置中的 navigationTimeout 选项或使用 browserContext.setDefaultNavigationTimeout()browserContext.setDefaultTimeout()page.setDefaultNavigationTimeout()page.setDefaultTimeout() 方法更改默认值。

Maximum operation time in milliseconds. Defaults to 0 - no timeout. The default value can be changed via navigationTimeout option in the config, or by using the browserContext.setDefaultNavigationTimeout(), browserContext.setDefaultTimeout(), page.setDefaultNavigationTimeout() or page.setDefaultTimeout() methods.

  • waitUntil "load"|"domcontentloaded"|"networkidle"|"commit"(可选)#

    waitUntil "load"|"domcontentloaded"|"networkidle"|"commit" (optional)#

    什么时候才认为操作成功,默认为 load。事件可以是:

    When to consider operation succeeded, defaults to load. Events can be either:

    • 'domcontentloaded' - 认为操作在 DOMContentLoaded 事件触发时完成。

      'domcontentloaded' - consider operation to be finished when the DOMContentLoaded event is fired.

    • 'load' - 认为操作在 load 事件触发时完成。

      'load' - consider operation to be finished when the load event is fired.

    • 'networkidle' - 不鼓励在至少 500 毫秒内没有网络连接时考虑操作完成。不要使用此方法进行测试,而是依靠网络断言来评估准备情况。

      'networkidle' - DISCOURAGED consider operation to be finished when there are no network connections for at least 500 ms. Don't use this method for testing, rely on web assertions to assess readiness instead.

    • 'commit' - 当收到网络响应并且文档开始加载时,认为操作完成。

      'commit' - consider operation to be finished when network response is received and the document started loading.

返回

Returns


route

Added in: v1.8 page.route

路由提供了修改页面触发的网络请求的功能。

Routing provides the capability to modify network requests that are made by a page.

一旦启用路由,每个与 url 模式匹配的请求都将停止,除非它继续、完成或中止。

Once routing is enabled, every request matching the url pattern will stall unless it's continued, fulfilled or aborted.

注意

如果响应是重定向,则仅针对第一个 url 调用处理程序。

The handler will only be called for the first url if the response is a redirect.

注意

page.route() 不会拦截 Service Worker 拦截的请求。参见 this 期。我们建议在使用请求拦截时通过将 Browser.newContext.serviceWorkers 设置为 'block' 来禁用 Service Worker。

page.route() will not intercept requests intercepted by Service Worker. See this issue. We recommend disabling Service Workers when using request interception by setting Browser.newContext.serviceWorkers to 'block'.

用法

Usage

中止所有图片请求的简单处理程序的示例:

An example of a naive handler that aborts all image requests:

const page = await browser.newPage();
await page.route('**/*.{png,jpg,jpeg}', route => route.abort());
await page.goto('https://example.com');
await browser.close();

或使用正则表达式模式的相同片段:

or the same snippet using a regex pattern instead:

const page = await browser.newPage();
await page.route(/(\.png$)|(\.jpg$)/, route => route.abort());
await page.goto('https://example.com');
await browser.close();

可以检查请求来决定路由操作。例如,模拟包含某些发布数据的所有请求,并保留所有其他请求不变:

It is possible to examine the request to decide the route action. For example, mocking all requests that contain some post data, and leaving all other requests as is:

await page.route('/api/**', route => {
if (route.request().postData().includes('my-string'))
route.fulfill({ body: 'mocked-data' });
else
route.continue();
});

当请求与两个处理程序匹配时,页面路由优先于浏览器上下文路由(使用 browserContext.route() 设置)。

Page routes take precedence over browser context routes (set up with browserContext.route()) when request matches both handlers.

要删除路由及其处理程序,你可以使用 page.unroute()

To remove a route with its handler you can use page.unroute().

注意

启用路由会禁用 http 缓存。

Enabling routing disables http cache.

参数

Arguments

通配符模式、正则表达式模式或谓词接收 URL 以在路由时进行匹配。当通过上下文选项提供 baseURL 并且传递的 URL 是路径时,它将通过 new URL() 构造函数合并。

A glob pattern, regex pattern or predicate receiving URL to match while routing. When a baseURL via the context options was provided and the passed URL is a path, it gets merged via the new URL() constructor.

处理程序函数来路由请求。

handler function to route the request.

  • options Object (optional)

    • times number (optional) Added in: v1.15#

路由应该多久使用一次。默认情况下每次都会使用它。

How often a route should be used. By default it will be used every time.


routeFromHAR

Added in: v1.23 page.routeFromHAR

如果指定,页面中触发的网络请求将从 HAR 文件提供服务。了解有关 从 HAR 重播 的更多信息。

If specified the network requests that are made in the page will be served from the HAR file. Read more about Replaying from HAR.

Playwright 不会处理 Service Worker 从 HAR 文件中拦截的请求。参见 this 期。我们建议在使用请求拦截时通过将 Browser.newContext.serviceWorkers 设置为 'block' 来禁用 Service Worker。

Playwright will not serve requests intercepted by Service Worker from the HAR file. See this issue. We recommend disabling Service Workers when using request interception by setting Browser.newContext.serviceWorkers to 'block'.

用法

Usage

await page.routeFromHAR(har);
await page.routeFromHAR(har, options);

参数

Arguments

带有预先记录的网络数据的 HAR 文件的路径。如果 path 是相对路径,则相对于当前工作目录进行解析。

Path to a HAR file with prerecorded network data. If path is a relative path, then it is resolved relative to the current working directory.

  • notFound "abort"|"fallback"(可选)#

    notFound "abort"|"fallback" (optional)#

    • 如果设置为 'abort',在 HAR 文件中找不到的任何请求都将被中止。

      If set to 'abort' any request not found in the HAR file will be aborted.

    • 如果设置为 'fallback',丢失的请求将被发送到网络。

      If set to 'fallback' missing requests will be sent to the network. 默认为中止。

    Defaults to abort.

如果指定,则使用实际网络信息更新给定的 HAR,而不是从文件提供服务。当调用 browserContext.close() 时,文件被写入磁盘。

If specified, updates the given HAR with the actual network information instead of serving from file. The file is written to disk when browserContext.close() is called.

  • updateContent "embed"|"attach"(可选) Added in: v1.32#

    updateContent "embed"|"attach" (optional) Added in: v1.32#

    用于控制资源内容管理的可选设置。如果指定了 attach,资源将作为单独的文件或条目保留在 ZIP 存档中。如果指定了 embed,内容将内联存储在 HAR 文件中。

    Optional setting to control resource content management. If attach is specified, resources are persisted as separate files or entries in the ZIP archive. If embed is specified, content is stored inline the HAR file.

  • updateMode "full"|"minimal"(可选) Added in: v1.32#

    updateMode "full"|"minimal" (optional) Added in: v1.32#

    当设置为 minimal 时,仅记录从 HAR 路由所需的信息。这会忽略从 HAR 重放时不使用的大小、计时、页面、cookie、安全性和其他类型的 HAR 信息。默认为 full

    When set to minimal, only record information necessary for routing from HAR. This omits sizes, timing, page, cookies, security and other types of HAR information that are not used when replaying from HAR. Defaults to full.

用于匹配请求 URL 的通配符模式、正则表达式或谓词。HAR 文件只会提供 URL 与模式匹配的请求。如果未指定,则所有请求均由 HAR 文件提供服务。

A glob pattern, regular expression or predicate to match the request URL. Only requests with URL matching the pattern will be served from the HAR file. If not specified, all requests are served from the HAR file.


screenshot

Added in: v1.8 page.screenshot

返回带有捕获的屏幕截图的缓冲区。

Returns the buffer with the captured screenshot.

用法

Usage

await page.screenshot();
await page.screenshot(options);

参数

Arguments

  • animations "disabled"|"allow"(可选)#

    animations "disabled"|"allow" (optional)#

    当设置为 "disabled" 时,停止 CSS 动画、CSS 转场和 Web 动画。动画根据其持续时间得到不同的处理:

    When set to "disabled", stops CSS animations, CSS transitions and Web Animations. Animations get different treatment depending on their duration:

    • 有限动画会快进完成,因此它们会触发 transitionend 事件。

      finite animations are fast-forwarded to completion, so they'll fire transitionend event.

    • 无限动画被取消到初始状态,然后在屏幕截图后播放。

      infinite animations are canceled to initial state, and then played over after the screenshot.

    默认为 "allow",不影响动画。

    Defaults to "allow" that leaves animations untouched.

  • caret "hide"|"initial"(可选)#

    caret "hide"|"initial" (optional)#

    当设置为 "hide" 时,屏幕截图将隐藏文本插入符。当设置为 "initial" 时,文本插入符行为将不会更改。默认为 "hide"

    When set to "hide", screenshot will hide text caret. When set to "initial", text caret behavior will not be changed. Defaults to "hide".

剪辑区域左上角的 x 坐标

x-coordinate of top-left corner of clip area

剪辑区域左上角的 y 坐标

y-coordinate of top-left corner of clip area

剪裁区域的宽度

width of clipping area

剪裁区域的高度

height of clipping area

指定对结果图片进行裁剪的对象。

An object which specifies clipping of the resulting image.

如果为 true,则截取完整可滚动页面的屏幕截图,而不是当前可见的视口。默认为 false

When true, takes a screenshot of the full scrollable page, instead of the currently visible viewport. Defaults to false.

指定截取屏幕截图时应屏蔽的定位器。被遮罩的元素将被一个粉色框 #FF00FF(由 maskColor 定制)覆盖,完全覆盖其边界框。

Specify locators that should be masked when the screenshot is taken. Masked elements will be overlaid with a pink box #FF00FF (customized by maskColor) that completely covers its bounding box.

  • maskColor string (optional) Added in: v1.35#

指定屏蔽元素的覆盖框的颜色,以 CSS 颜色格式 为单位。默认颜色为粉色 #FF00FF

Specify the color of the overlay box for masked elements, in CSS color format. Default color is pink #FF00FF.

隐藏默认的白色背景并允许捕获透明的屏幕截图。不适用于 jpeg 图片。默认为 false

Hides default white background and allows capturing screenshots with transparency. Not applicable to jpeg images. Defaults to false.

保存图片的文件路径。屏幕截图类型将从文件扩展名推断出来。如果 path 是相对路径,则相对于当前工作目录进行解析。如果未提供路径,图片将不会保存到磁盘。

The file path to save the image to. The screenshot type will be inferred from file extension. If path is a relative path, then it is resolved relative to the current working directory. If no path is provided, the image won't be saved to the disk.

图片质量,介于 0-100 之间。不适用于 png 图片。

The quality of the image, between 0-100. Not applicable to png images.

  • scale "css"|"device"(可选)#

    scale "css"|"device" (optional)#

    当设置为 "css" 时,屏幕截图页面上的每个 css 像素将有一个像素。对于高 dpi 设备,这将使屏幕截图保持较小。使用 "device" 选项将为每个设备像素生成一个像素,因此高 dpi 设备的屏幕截图将是原来的两倍甚至更大。

    When set to "css", screenshot will have a single pixel per each css pixel on the page. For high-dpi devices, this will keep screenshots small. Using "device" option will produce a single pixel per each device pixel, so screenshots of high-dpi devices will be twice as large or even larger.

    默认为 "device"

    Defaults to "device".

    • style string (optional) Added in: v1.41#

制作屏幕截图时要应用的样式表文本。你可以在此处隐藏动态元素、使元素不可见或更改其属性以帮助你创建可重复的屏幕截图。该样式表穿透 Shadow DOM 并应用于内部框架。

Text of the stylesheet to apply while making the screenshot. This is where you can hide dynamic elements, make elements invisible or change their properties to help you creating repeatable screenshots. This stylesheet pierces the Shadow DOM and applies to the inner frames.

最长时间(以毫秒为单位)。默认为 0 - 没有超时。可以通过配置中的 actionTimeout 选项或使用 browserContext.setDefaultTimeout()page.setDefaultTimeout() 方法更改默认值。

Maximum time in milliseconds. Defaults to 0 - no timeout. The default value can be changed via actionTimeout option in the config, or by using the browserContext.setDefaultTimeout() or page.setDefaultTimeout() methods.

  • type "png"|"jpeg"(可选)#

    type "png"|"jpeg" (optional)#

    指定截图类型,默认为 png

    Specify screenshot type, defaults to png.

返回

Returns


setContent

Added in: v1.8 page.setContent

该方法内部调用 document.write(),继承其所有特定特性和行为。

This method internally calls document.write(), inheriting all its specific characteristics and behaviors.

用法

Usage

await page.setContent(html);
await page.setContent(html, options);

参数

Arguments

要分配给页面的 HTML 标记。

HTML markup to assign to the page.

最大操作时间(以毫秒为单位)。默认为 0 - 没有超时。可以通过配置中的 navigationTimeout 选项或使用 browserContext.setDefaultNavigationTimeout()browserContext.setDefaultTimeout()page.setDefaultNavigationTimeout()page.setDefaultTimeout() 方法更改默认值。

Maximum operation time in milliseconds. Defaults to 0 - no timeout. The default value can be changed via navigationTimeout option in the config, or by using the browserContext.setDefaultNavigationTimeout(), browserContext.setDefaultTimeout(), page.setDefaultNavigationTimeout() or page.setDefaultTimeout() methods.

  • waitUntil "load"|"domcontentloaded"|"networkidle"|"commit"(可选)#

    waitUntil "load"|"domcontentloaded"|"networkidle"|"commit" (optional)#

    什么时候才认为操作成功,默认为 load。事件可以是:

    When to consider operation succeeded, defaults to load. Events can be either:

    • 'domcontentloaded' - 认为操作在 DOMContentLoaded 事件触发时完成。

      'domcontentloaded' - consider operation to be finished when the DOMContentLoaded event is fired.

    • 'load' - 认为操作在 load 事件触发时完成。

      'load' - consider operation to be finished when the load event is fired.

    • 'networkidle' - 不鼓励在至少 500 毫秒内没有网络连接时考虑操作完成。不要使用此方法进行测试,而是依靠网络断言来评估准备情况。

      'networkidle' - DISCOURAGED consider operation to be finished when there are no network connections for at least 500 ms. Don't use this method for testing, rely on web assertions to assess readiness instead.

    • 'commit' - 当收到网络响应并且文档开始加载时,认为操作完成。

      'commit' - consider operation to be finished when network response is received and the document started loading.


setDefaultNavigationTimeout

Added in: v1.8 page.setDefaultNavigationTimeout

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

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

用法

Usage

page.setDefaultNavigationTimeout(timeout);

参数

Arguments

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

Maximum navigation time in milliseconds


setDefaultTimeout

Added in: v1.8 page.setDefaultTimeout

此设置将更改所有接受 timeout 选项的方法的默认最大时间。

This setting will change the default maximum time for all the methods accepting timeout option.

用法

Usage

page.setDefaultTimeout(timeout);

参数

Arguments

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

Maximum time in milliseconds


setExtraHTTPHeaders

Added in: v1.8 page.setExtraHTTPHeaders

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

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

注意

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

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

用法

Usage

await page.setExtraHTTPHeaders(headers);

参数

Arguments

包含随每个请求发送的附加 HTTP 标头的对象。所有标头值都必须是字符串。

An object containing additional HTTP headers to be sent with every request. All header values must be strings.


setViewportSize

Added in: v1.8 page.setViewportSize

在单个浏览器中有多个页面的情况下,每个页面可以有自己的视口大小。但是,browser.newContext() 允许同时为上下文中的所有页面设置视口大小(以及更多)。

In the case of multiple pages in a single browser, each page can have its own viewport size. However, browser.newContext() allows to set viewport size (and more) for all pages in the context at once.

page.setViewportSize() 将调整页面大小。许多网站不希望手机改变大小,因此你应该在导航到页面之前设置视口大小。page.setViewportSize() 还将重置 screen 大小,如果需要更好地控制这些属性,请使用 browser.newContext()screenviewport 参数。

page.setViewportSize() will resize the page. A lot of websites don't expect phones to change size, so you should set the viewport size before navigating to the page. page.setViewportSize() will also reset screen size, use browser.newContext() with screen and viewport parameters if you need better control of these properties.

用法

Usage

const page = await browser.newPage();
await page.setViewportSize({
width: 640,
height: 480,
});
await page.goto('https://example.com');

参数

Arguments

页面宽度(以像素为单位)。

page width in pixels.

页面高度(以像素为单位)。

page height in pixels.


title

Added in: v1.8 page.title

返回页面的标题。

Returns the page's title.

用法

Usage

await page.title();

返回

Returns


unroute

Added in: v1.8 page.unroute

删除使用 page.route() 创建的路由。当不指定 handler 时,删除 url 的所有路由。

Removes a route created with page.route(). When handler is not specified, removes all routes for the url.

用法

Usage

await page.unroute(url);
await page.unroute(url, handler);

参数

Arguments

通配符模式、正则表达式模式或谓词接收 URL 以在路由时进行匹配。

A glob pattern, regex pattern or predicate receiving URL to match while routing.

用于路由请求的可选处理程序函数。

Optional handler function to route the request.


unrouteAll

Added in: v1.41 page.unrouteAll

删除使用 page.route()page.routeFromHAR() 创建的所有路由。

Removes all routes created with page.route() and page.routeFromHAR().

用法

Usage

await page.unrouteAll();
await page.unrouteAll(options);

参数

Arguments

  • behavior "wait"|"ignoreErrors"|"default"(可选)#

    behavior "wait"|"ignoreErrors"|"default" (optional)#

    指定是否等待已经运行的处理程序以及如果它们抛出错误该怎么办:

    Specifies wether to wait for already running handlers and what to do if they throw errors:

    • 'default' - 不要等待当前处理程序调用(如果有)完成,如果未路由的处理程序抛出,可能会导致未处理的错误

      'default' - do not wait for current handler calls (if any) to finish, if unrouted handler throws, it may result in unhandled error

    • 'wait' - 等待当前处理程序调用(如果有)完成

      'wait' - wait for current handler calls (if any) to finish

    • 'ignoreErrors' - 不等待当前处理程序调用(如果有)完成,取消路由后处理程序抛出的所有错误都会被静默捕获

      'ignoreErrors' - do not wait for current handler calls (if any) to finish, all errors thrown by the handlers after unrouting are silently caught


url

Added in: v1.8 page.url

用法

Usage

page.url();

返回

Returns


video

Added in: v1.8 page.video

与此页面关联的视频对象。

Video object associated with this page.

用法

Usage

page.video();

返回

Returns


viewportSize

Added in: v1.8 page.viewportSize

用法

Usage

page.viewportSize();

返回

Returns

页面宽度(以像素为单位)。

page width in pixels.

页面高度(以像素为单位)。

page height in pixels.


waitForEvent

Added in: v1.8 page.waitForEvent

等待事件触发并将其值传递给谓词函数。当谓词返回真值时返回。如果在事件触发之前关闭页面,将引发错误。返回事件数据值。

Waits for event to fire and passes its value into the predicate function. Returns when the predicate returns truthy value. Will throw an error if the page is closed before the event is fired. Returns the event data value.

用法

Usage

// Start waiting for download before clicking. Note no await.
const downloadPromise = page.waitForEvent('download');
await page.getByText('Download file').click();
const download = await downloadPromise;

参数

Arguments

事件名称,通常传递到 *.on(event) 中。

Event name, same one typically passed into *.on(event).

接收事件数据并在等待解决时解析为真值。

Receives the event data and resolves to truthy value when the waiting should resolve.

等待的最长时间(以毫秒为单位)。默认为 0 - 没有超时。可以通过配置中的 actionTimeout 选项或使用 browserContext.setDefaultTimeout()page.setDefaultTimeout() 方法更改默认值。

Maximum time to wait for in milliseconds. Defaults to 0 - no timeout. The default value can be changed via actionTimeout option in the config, or by using the browserContext.setDefaultTimeout() or page.setDefaultTimeout() methods.

接收事件的谓词或选项对象。可选的。

Either a predicate that receives an event or an options object. Optional.

接收事件数据并在等待解决时解析为真值。

Receives the event data and resolves to truthy value when the waiting should resolve.

返回

Returns


waitForFunction

Added in: v1.8 page.waitForFunction

pageFunction 返回真值时返回。它解析为真实值的 JSHandle。

Returns when the pageFunction returns a truthy value. It resolves to a JSHandle of the truthy value.

用法

Usage

page.waitForFunction() 可用于观察视口大小的变化:

The page.waitForFunction() can be used to observe viewport size change:

const { webkit } = require('playwright');  // Or 'chromium' or 'firefox'.

(async () => {
const browser = await webkit.launch();
const page = await browser.newPage();
const watchDog = page.waitForFunction(() => window.innerWidth < 100);
await page.setViewportSize({ width: 50, height: 50 });
await watchDog;
await browser.close();
})();

要将参数传递给 page.waitForFunction() 函数的谓词:

To pass an argument to the predicate of page.waitForFunction() function:

const selector = '.foo';
await page.waitForFunction(selector => !!document.querySelector(selector), selector);

参数

Arguments

要在页面上下文中评估的函数。

Function to be evaluated in the page context.

传递给 pageFunction 的可选参数。

Optional argument to pass to pageFunction.

如果 polling'raf',那么在 requestAnimationFrame 回调中不断执行 pageFunction。如果 polling 是一个数字,则将其视为执行函数的时间间隔(以毫秒为单位)。默认为 raf

If polling is 'raf', then pageFunction is constantly executed in requestAnimationFrame callback. If polling is a number, then it is treated as an interval in milliseconds at which the function would be executed. Defaults to raf.

等待的最长时间(以毫秒为单位)。默认为 0 - 没有超时。可以通过配置中的 actionTimeout 选项或使用 browserContext.setDefaultTimeout()page.setDefaultTimeout() 方法更改默认值。

Maximum time to wait for in milliseconds. Defaults to 0 - no timeout. The default value can be changed via actionTimeout option in the config, or by using the browserContext.setDefaultTimeout() or page.setDefaultTimeout() methods.

返回

Returns


waitForLoadState

Added in: v1.8 page.waitForLoadState

当达到所需的负载状态时返回。

Returns when the required load state has been reached.

当页面达到所需的加载状态(默认情况下为 load)时,此问题就会解决。调用此方法时必须已提交导航。如果当前文档已达到所需状态,则立即解决。

This resolves when the page reaches a required load state, load by default. The navigation must have been committed when this method is called. If current document has already reached the required state, resolves immediately.

用法

Usage

await page.getByRole('button').click(); // Click triggers navigation.
await page.waitForLoadState(); // The promise resolves after 'load' event.
const popupPromise = page.waitForEvent('popup');
await page.getByRole('button').click(); // Click triggers a popup.
const popup = await popupPromise;
await popup.waitForLoadState('domcontentloaded'); // Wait for the 'DOMContentLoaded' event.
console.log(await popup.title()); // Popup is ready to use.

参数

Arguments

  • state "load"|"domcontentloaded"|"networkidle"(可选)#

    state "load"|"domcontentloaded"|"networkidle" (optional)#

    等待的可选加载状态,默认为 load。如果在加载当前文档时已经达到该状态,则该方法立即解析。可以是以下之一:

    Optional load state to wait for, defaults to load. If the state has been already reached while loading current document, the method resolves immediately. Can be one of:

    • 'load' - 等待 load 事件被触发。

      'load' - wait for the load event to be fired.

    • 'domcontentloaded' - 等待 DOMContentLoaded 事件被触发。

      'domcontentloaded' - wait for the DOMContentLoaded event to be fired.

    • 'networkidle' - 不建议等待至少 500 毫秒没有网络连接。不要使用此方法进行测试,而是依靠网络断言来评估准备情况。

      'networkidle' - DISCOURAGED wait until there are no network connections for at least 500 ms. Don't use this method for testing, rely on web assertions to assess readiness instead.

最大操作时间(以毫秒为单位)。默认为 0 - 没有超时。可以通过配置中的 navigationTimeout 选项或使用 browserContext.setDefaultNavigationTimeout()browserContext.setDefaultTimeout()page.setDefaultNavigationTimeout()page.setDefaultTimeout() 方法更改默认值。

Maximum operation time in milliseconds. Defaults to 0 - no timeout. The default value can be changed via navigationTimeout option in the config, or by using the browserContext.setDefaultNavigationTimeout(), browserContext.setDefaultTimeout(), page.setDefaultNavigationTimeout() or page.setDefaultTimeout() methods.


waitForRequest

Added in: v1.8 page.waitForRequest

等待匹配的请求并返回。有关事件的更多详细信息,请参阅 等待事件

Waits for the matching request and returns it. See waiting for event for more details about events.

用法

Usage

// Start waiting for request before clicking. Note no await.
const requestPromise = page.waitForRequest('https://example.com/resource');
await page.getByText('trigger request').click();
const request = await requestPromise;

// Alternative way with a predicate. Note no await.
const requestPromise = page.waitForRequest(request =>
request.url() === 'https://example.com' && request.method() === 'GET',
);
await page.getByText('trigger request').click();
const request = await requestPromise;

参数

Arguments

请求 URL 字符串、正则表达式或谓词接收 请求 对象。

Request URL string, regex or predicate receiving Request object.

最大等待时间(以毫秒为单位),默认为 30 秒,通过 0 禁用超时。可以使用 page.setDefaultTimeout() 方法更改默认值。

Maximum wait time in milliseconds, defaults to 30 seconds, pass 0 to disable the timeout. The default value can be changed by using the page.setDefaultTimeout() method.

返回

Returns


waitForResponse

Added in: v1.8 page.waitForResponse

返回匹配的响应。有关事件的更多详细信息,请参阅 等待事件

Returns the matched response. See waiting for event for more details about events.

用法

Usage

// Start waiting for response before clicking. Note no await.
const responsePromise = page.waitForResponse('https://example.com/resource');
await page.getByText('trigger response').click();
const response = await responsePromise;

// Alternative way with a predicate. Note no await.
const responsePromise = page.waitForResponse(response =>
response.url() === 'https://example.com' && response.status() === 200
);
await page.getByText('trigger response').click();
const response = await responsePromise;

参数

Arguments

请求 URL 字符串、正则表达式或谓词接收 响应 对象。当通过上下文选项提供 baseURL 并且传递的 URL 是路径时,它将通过 new URL() 构造函数合并。

Request URL string, regex or predicate receiving Response object. When a baseURL via the context options was provided and the passed URL is a path, it gets merged via the new URL() constructor.

最大等待时间(以毫秒为单位),默认为 30 秒,通过 0 禁用超时。可以使用 browserContext.setDefaultTimeout()page.setDefaultTimeout() 方法更改默认值。

Maximum wait time in milliseconds, defaults to 30 seconds, pass 0 to disable the timeout. The default value can be changed by using the browserContext.setDefaultTimeout() or page.setDefaultTimeout() methods.

返回

Returns


waitForURL

Added in: v1.11 page.waitForURL

等待主框架导航到给定的 URL。

Waits for the main frame to navigate to the given URL.

用法

Usage

await page.click('a.delayed-navigation'); // Clicking the link will indirectly cause a navigation
await page.waitForURL('**/target.html');

参数

Arguments

在等待导航时接收 URL 进行匹配的通配符模式、正则表达式模式或谓词。请注意,如果参数是不带通配符的字符串,则该方法将等待导航到与该字符串完全相同的 URL。

A glob pattern, regex pattern or predicate receiving URL to match while waiting for the navigation. Note that if the parameter is a string without wildcard characters, the method will wait for navigation to URL that is exactly equal to the string.

最大操作时间(以毫秒为单位)。默认为 0 - 没有超时。可以通过配置中的 navigationTimeout 选项或使用 browserContext.setDefaultNavigationTimeout()browserContext.setDefaultTimeout()page.setDefaultNavigationTimeout()page.setDefaultTimeout() 方法更改默认值。

Maximum operation time in milliseconds. Defaults to 0 - no timeout. The default value can be changed via navigationTimeout option in the config, or by using the browserContext.setDefaultNavigationTimeout(), browserContext.setDefaultTimeout(), page.setDefaultNavigationTimeout() or page.setDefaultTimeout() methods.

  • waitUntil "load"|"domcontentloaded"|"networkidle"|"commit"(可选)#

    waitUntil "load"|"domcontentloaded"|"networkidle"|"commit" (optional)#

    什么时候才认为操作成功,默认为 load。事件可以是:

    When to consider operation succeeded, defaults to load. Events can be either:

    • 'domcontentloaded' - 认为操作在 DOMContentLoaded 事件触发时完成。

      'domcontentloaded' - consider operation to be finished when the DOMContentLoaded event is fired.

    • 'load' - 认为操作在 load 事件触发时完成。

      'load' - consider operation to be finished when the load event is fired.

    • 'networkidle' - 不鼓励在至少 500 毫秒内没有网络连接时考虑操作完成。不要使用此方法进行测试,而是依靠网络断言来评估准备情况。

      'networkidle' - DISCOURAGED consider operation to be finished when there are no network connections for at least 500 ms. Don't use this method for testing, rely on web assertions to assess readiness instead.

    • 'commit' - 当收到网络响应并且文档开始加载时,认为操作完成。

      'commit' - consider operation to be finished when network response is received and the document started loading.


workers

Added in: v1.8 page.workers

此方法返回与该页面关联的所有专用 WebWorkers

This method returns all of the dedicated WebWorkers associated with the page.

注意

这不包含 ServiceWorkers

This does not contain ServiceWorkers

用法

Usage

page.workers();

返回

Returns


属性

Properties

coverage

Added in: v1.8 page.coverage
注意

仅适用于 Chromium atm。

Only available for Chromium atm.

浏览器特定的 Coverage 实现。详细信息请参见 覆盖范围

Browser-specific Coverage implementation. See Coverage for more details.

用法

Usage

page.coverage

类型

Type


keyboard

Added in: v1.8 page.keyboard

用法

Usage

page.keyboard

类型

Type


mouse

Added in: v1.8 page.mouse

用法

Usage

page.mouse

类型

Type


request

Added in: v1.16 page.request

与此页面关联的 API 测试助手。此方法返回与页面上下文中的 browserContext.request 相同的实例。详细信息请参见 browserContext.request

API testing helper associated with this page. This method returns the same instance as browserContext.request on the page's context. See browserContext.request for more details.

用法

Usage

page.request

类型

Type


touchscreen

Added in: v1.8 page.touchscreen

用法

Usage

page.touchscreen

类型

Type


事件

Events

on('close')

Added in: v1.8 page.on('close')

页面关闭时触发。

Emitted when the page closes.

用法

Usage

page.on('close', data => {});

事件数据

Event data


on('console')

Added in: v1.8 page.on('console')

当页面内的 JavaScript 调用控制台 API 方法之一时触发,例如 console.logconsole.dir。如果页面抛出错误或警告,也会触发。

Emitted when JavaScript within the page calls one of console API methods, e.g. console.log or console.dir. Also emitted if the page throws an error or a warning.

传递到 console.log 的参数可在 ConsoleMessage 事件处理程序参数上使用。

The arguments passed into console.log are available on the ConsoleMessage event handler argument.

用法

Usage

page.on('console', async msg => {
const values = [];
for (const arg of msg.args())
values.push(await arg.jsonValue());
console.log(...values);
});
await page.evaluate(() => console.log('hello', 5, { foo: 'bar' }));

事件数据

Event data


on('crash')

Added in: v1.8 page.on('crash')

页面崩溃时触发。如果浏览器页面尝试分配过多内存,则可能会崩溃。当页面崩溃时,正在进行的和后续的操作将会抛出。

Emitted when the page crashes. Browser pages might crash if they try to allocate too much memory. When the page crashes, ongoing and subsequent operations will throw.

处理崩溃最常见的方法是捕获异常:

The most common way to deal with crashes is to catch an exception:

try {
// Crash might happen during a click.
await page.click('button');
// Or while waiting for an event.
await page.waitForEvent('popup');
} catch (e) {
// When the page crashes, exception message contains 'crash'.
}

用法

Usage

page.on('crash', data => {});

事件数据

Event data


on('dialog')

Added in: v1.8 page.on('dialog')

当 JavaScript 对话框出现时触发,例如 alertpromptconfirmbeforeunload。监听者必须选择 dialog.accept()dialog.dismiss() 对话 - 否则页面将 freeze 等待对话框,并且单击等操作将永远不会完成。

Emitted when a JavaScript dialog appears, such as alert, prompt, confirm or beforeunload. Listener must either dialog.accept() or dialog.dismiss() the dialog - otherwise the page will freeze waiting for the dialog, and actions like click will never finish.

用法

Usage

page.on('dialog', dialog => {
dialog.accept();
});
注意

当没有 page.on('dialog')browserContext.on('dialog') 监听器存在时,所有对话框都会自动关闭。

When no page.on('dialog') or browserContext.on('dialog') listeners are present, all dialogs are automatically dismissed.

事件数据

Event data


on('domcontentloaded')

Added in: v1.9 page.on('domcontentloaded')

当调度 JavaScript DOMContentLoaded 事件时触发。

Emitted when the JavaScript DOMContentLoaded event is dispatched.

用法

Usage

page.on('domcontentloaded', data => {});

事件数据

Event data


on('download')

Added in: v1.8 page.on('download')

附件下载开始时触发。用户可以通过传递的 下载 实例访问对下载内容的基本文件操作。

Emitted when attachment download started. User can access basic file operations on downloaded content via the passed Download instance.

用法

Usage

page.on('download', data => {});

事件数据

Event data


on('filechooser')

Added in: v1.9 page.on('filechooser')

当应该出现文件选择器时触发,例如单击 <input type=file>。Playwright 可以通过使用 fileChooser.setFiles() 设置输入文件来响应它,然后可以上传这些文件。

Emitted when a file chooser is supposed to appear, such as after clicking the <input type=file>. Playwright can respond to it via setting the input files using fileChooser.setFiles() that can be uploaded after that.

page.on('filechooser', async fileChooser => {
await fileChooser.setFiles(path.join(__dirname, '/tmp/myfile.pdf'));
});

用法

Usage

page.on('filechooser', data => {});

事件数据

Event data


on('frameattached')

Added in: v1.9 page.on('frameattached')

当附加框架时触发。

Emitted when a frame is attached.

用法

Usage

page.on('frameattached', data => {});

事件数据

Event data


on('framedetached')

Added in: v1.9 page.on('framedetached')

当框架分离时触发。

Emitted when a frame is detached.

用法

Usage

page.on('framedetached', data => {});

事件数据

Event data


on('framenavigated')

Added in: v1.9 page.on('framenavigated')

当框架导航到新的 url 时触发。

Emitted when a frame is navigated to a new url.

用法

Usage

page.on('framenavigated', data => {});

事件数据

Event data


on('load')

Added in: v1.8 page.on('load')

当调度 JavaScript load 事件时触发。

Emitted when the JavaScript load event is dispatched.

用法

Usage

page.on('load', data => {});

事件数据

Event data


on('pageerror')

Added in: v1.9 page.on('pageerror')

当页面内发生未捕获的异常时触发。

Emitted when an uncaught exception happens within the page.

// Log all uncaught errors to the terminal
page.on('pageerror', exception => {
console.log(`Uncaught exception: "${exception}"`);
});

// Navigate to a page with an exception.
await page.goto('data:text/html,<script>throw new Error("Test")</script>');

用法

Usage

page.on('pageerror', data => {});

事件数据

Event data


on('popup')

Added in: v1.8 page.on('popup')

当页面打开新选项卡或窗口时触发。除了 browserContext.on('page') 之外,还会触发此事件,但仅针对与此页面相关的弹出窗口。

Emitted when the page opens a new tab or window. This event is emitted in addition to the browserContext.on('page'), but only for popups relevant to this page.

该页面最早可用的时刻是导航到初始 URL 时。例如,当使用 window.open('http://example.com') 打开弹出窗口时,当对 "http://example.com" 的网络请求完成并且其响应已开始在弹出窗口中加载时,将触发此事件。

The earliest moment that page is available is when it has navigated to the initial url. For example, when opening a popup with window.open('http://example.com'), this event will fire when the network request to "http://example.com" is done and its response has started loading in the popup.

// Start waiting for popup before clicking. Note no await.
const popupPromise = page.waitForEvent('popup');
await page.getByText('open the popup').click();
const popup = await popupPromise;
console.log(await popup.evaluate('location.href'));
注意

使用 page.waitForLoadState() 等待页面进入特定状态(在大多数情况下你不需要它)。

Use page.waitForLoadState() to wait until the page gets to a particular state (you should not need it in most cases).

用法

Usage

page.on('popup', data => {});

事件数据

Event data


on('request')

Added in: v1.8 page.on('request')

当页面触发请求时触发。request 对象是只读的。为了拦截和改变请求,请参阅 page.route()browserContext.route()

Emitted when a page issues a request. The request object is read-only. In order to intercept and mutate requests, see page.route() or browserContext.route().

用法

Usage

page.on('request', data => {});

事件数据

Event data


on('requestfailed')

Added in: v1.9 page.on('requestfailed')

当请求失败时触发,例如超时。

Emitted when a request fails, for example by timing out.

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

从 HTTP 角度来看,HTTP 错误响应(例如 404 或 503)仍然是成功响应,因此请求将通过 page.on('requestfinished') 事件完成,而不是通过 page.on('requestfailed') 事件完成。仅当客户端无法从服务器获取 HTTP 响应时,请求才会被视为失败,例如 由于网络错误 net::ERR_FAILED。

HTTP Error responses, such as 404 or 503, are still successful responses from HTTP standpoint, so request will complete with page.on('requestfinished') event and not with page.on('requestfailed'). A request will only be considered failed when the client cannot get an HTTP response from the server, e.g. due to network error net::ERR_FAILED.

用法

Usage

page.on('requestfailed', data => {});

事件数据

Event data


on('requestfinished')

Added in: v1.9 page.on('requestfinished')

下载响应正文后请求成功完成时触发。对于成功响应,事件顺序为 requestresponserequestfinished

Emitted when a request finishes successfully after downloading the response body. For a successful response, the sequence of events is request, response and requestfinished.

用法

Usage

page.on('requestfinished', data => {});

事件数据

Event data


on('response')

Added in: v1.8 page.on('response')

当收到请求的 response 状态和标头时触发。对于成功响应,事件顺序为 requestresponserequestfinished

Emitted when response status and headers are received for a request. For a successful response, the sequence of events is request, response and requestfinished.

用法

Usage

page.on('response', data => {});

事件数据

Event data


on('websocket')

Added in: v1.9 page.on('websocket')

发送 WebSocket 请求时触发。

Emitted when WebSocket request is sent.

用法

Usage

page.on('websocket', data => {});

事件数据

Event data


on('worker')

Added in: v1.8 page.on('worker')

当页面生成专用 WebWorker 时触发。

Emitted when a dedicated WebWorker is spawned by the page.

用法

Usage

page.on('worker', data => {});

事件数据

Event data


已弃用

Deprecated

$ {#}

Added in: v1.9 page.$
劝阻

请改用基于定位器的 page.locator()。了解有关 locators 的更多信息。

Use locator-based page.locator() instead. Read more about locators.

该方法在页面中查找与指定选择器匹配的元素。如果没有元素与选择器匹配,则返回值解析为 null。要等待页面上的元素,请使用 locator.waitFor()

The method finds an element matching the specified selector within the page. If no elements match the selector, the return value resolves to null. To wait for an element on the page, use locator.waitFor().

用法

Usage

await page.$(selector);
await page.$(selector, options);

参数

Arguments

要查询的选择器。

A selector to query for.

  • options Object (optional)

    • strict boolean (optional) Added in: v1.14#

如果为 true,则调用需要选择器解析为单个元素。如果给定的选择器解析为多个元素,则调用会引发异常。

When true, the call requires selector to resolve to a single element. If given selector resolves to more than one element, the call throws an exception.

返回

Returns


$$

Added in: v1.9 page.$$
劝阻

请改用基于定位器的 page.locator()。了解有关 locators 的更多信息。

Use locator-based page.locator() instead. Read more about locators.

该方法查找页面内与指定选择器匹配的所有元素。如果没有元素与选择器匹配,则返回值解析为 []

The method finds all elements matching the specified selector within the page. If no elements match the selector, the return value resolves to [].

用法

Usage

await page.$$(selector);

参数

Arguments

要查询的选择器。

A selector to query for.

返回

Returns


$eval

Added in: v1.9 page.$eval
劝阻

此方法不会等待元素通过可操作性检查,因此可能导致不稳定的测试。请改用 locator.evaluate()、其他 定位器 辅助方法或 Web 优先断言。

This method does not wait for the element to pass actionability checks and therefore can lead to the flaky tests. Use locator.evaluate(), other Locator helper methods or web-first assertions instead.

该方法在页面中查找与指定选择器匹配的元素,并将其作为第一个参数传递给 pageFunction。如果没有元素与选择器匹配,该方法将引发错误。返回 pageFunction 的值。

The method finds an element matching the specified selector within the page and passes it as a first argument to pageFunction. If no elements match the selector, the method throws an error. Returns the value of pageFunction.

如果 pageFunction 返回 Promise,那么 page.$eval() 将等待 Promise 解析并返回其值。

If pageFunction returns a Promise, then page.$eval() would wait for the promise to resolve and return its value.

用法

Usage

const searchValue = await page.$eval('#search', el => el.value);
const preloadHref = await page.$eval('link[rel=preload]', el => el.href);
const html = await page.$eval('.main-container', (e, suffix) => e.outerHTML + suffix, 'hello');
// In TypeScript, this example requires an explicit type annotation (HTMLLinkElement) on el:
const preloadHrefTS = await page.$eval('link[rel=preload]', (el: HTMLLinkElement) => el.href);

参数

Arguments

要查询的选择器。

A selector to query for.

要在页面上下文中评估的函数。

Function to be evaluated in the page context.

传递给 pageFunction 的可选参数。

Optional argument to pass to pageFunction.

  • options Object (optional)

    • strict boolean (optional) Added in: v1.14#

如果为 true,则调用需要选择器解析为单个元素。如果给定的选择器解析为多个元素,则调用会引发异常。

When true, the call requires selector to resolve to a single element. If given selector resolves to more than one element, the call throws an exception.

返回

Returns


$$eval

Added in: v1.9 page.$$eval
劝阻

在大多数情况下,locator.evaluateAll()、其他 定位器 辅助方法和 Web 优先断言做得更好。

In most cases, locator.evaluateAll(), other Locator helper methods and web-first assertions do a better job.

该方法查找页面内与指定选择器匹配的所有元素,并将匹配元素的数组作为第一个参数传递给 pageFunction。返回 pageFunction 调用的结果。

The method finds all elements matching the specified selector within the page and passes an array of matched elements as a first argument to pageFunction. Returns the result of pageFunction invocation.

如果 pageFunction 返回 Promise,那么 page.$$eval() 将等待 Promise 解析并返回其值。

If pageFunction returns a Promise, then page.$$eval() would wait for the promise to resolve and return its value.

用法

Usage

const divCounts = await page.$$eval('div', (divs, min) => divs.length >= min, 10);

参数

Arguments

要查询的选择器。

A selector to query for.

要在页面上下文中评估的函数。

Function to be evaluated in the page context.

传递给 pageFunction 的可选参数。

Optional argument to pass to pageFunction.

返回

Returns


accessibility

Added in: v1.8 page.accessibility
已弃用

此属性不鼓励。如果你需要测试页面可访问性,请使用其他库,例如 Axe。请参阅我们的 Node.js guide 以了解与 Axe 的集成。

This property is discouraged. Please use other libraries such as Axe if you need to test page accessibility. See our Node.js guide for integration with Axe.

用法

Usage

page.accessibility

类型

Type


check

Added in: v1.8 page.check
劝阻

请改用基于定位器的 locator.check()。了解有关 locators 的更多信息。

Use locator-based locator.check() instead. Read more about locators.

该方法通过执行以下步骤来检查与 selector 匹配的元素:

This method checks an element matching selector by performing the following steps:

  1. 查找与 selector 匹配的元素。如果没有,请等待,直到将匹配的元素附加到 DOM。

    Find an element matching selector. If there is none, wait until a matching element is attached to the DOM.

  2. 确保匹配的元素是复选框或单选输入。如果不是,该方法将抛出异常。如果该元素已被检查,则此方法立即返回。

    Ensure that matched element is a checkbox or a radio input. If not, this method throws. If the element is already checked, this method returns immediately.

  3. 等待 actionability 检查匹配的元素,除非设置了 force 选项。如果在检查期间该元素被分离,则会重试整个操作。

    Wait for actionability checks on the matched element, unless force option is set. If the element is detached during the checks, the whole action is retried.

  4. 如果需要,将元素滚动到视图中。

    Scroll the element into view if needed.

  5. 使用 page.mouse 单击元素的中心。

    Use page.mouse to click in the center of the element.

  6. 等待启动的导航成功或失败,除非设置了 noWaitAfter 选项。

    Wait for initiated navigations to either succeed or fail, unless noWaitAfter option is set.

  7. 确保现在已检查该元素。如果不是,该方法将抛出异常。

    Ensure that the element is now checked. If not, this method throws.

当所有组合步骤在指定的 timeout 时间内尚未完成时,此方法将抛出 TimeoutError。传递零超时会禁用此功能。

When all steps combined have not finished during the specified timeout, this method throws a TimeoutError. Passing zero timeout disables this.

用法

Usage

await page.check(selector);
await page.check(selector, options);

参数

Arguments

用于搜索元素的选择器。如果有多个元素满足选择器,则将使用第一个元素。

A selector to search for an element. If there are multiple elements satisfying the selector, the first will be used.

是否绕过 actionability 检查。默认为 false

Whether to bypass the actionability checks. Defaults to false.

启动导航的操作正在等待这些导航发生并开始加载页面。你可以通过设置此标志来选择不等待。仅在特殊情况下才需要此选项,例如导航到无法访问的页面。默认为 false

Actions that initiate navigations are waiting for these navigations to happen and for pages to start loading. You can opt out of waiting via setting this flag. You would only need this option in the exceptional cases such as navigating to inaccessible pages. Defaults to false.

相对于元素填充框左上角使用的点。如果未指定,则使用元素的一些可见点。

A point to use relative to the top-left corner of element padding box. If not specified, uses some visible point of the element.

  • strict boolean (optional) Added in: v1.14#

如果为 true,则调用需要选择器解析为单个元素。如果给定的选择器解析为多个元素,则调用会引发异常。

When true, the call requires selector to resolve to a single element. If given selector resolves to more than one element, the call throws an exception.

最长时间(以毫秒为单位)。默认为 0 - 没有超时。可以通过配置中的 actionTimeout 选项或使用 browserContext.setDefaultTimeout()page.setDefaultTimeout() 方法更改默认值。

Maximum time in milliseconds. Defaults to 0 - no timeout. The default value can be changed via actionTimeout option in the config, or by using the browserContext.setDefaultTimeout() or page.setDefaultTimeout() methods.

  • trial boolean (optional) Added in: v1.11#

设置后,此方法仅执行 actionability 检查并跳过该操作。默认为 false。等待元素准备好执行操作而不执行该操作很有用。

When set, this method only performs the actionability checks and skips the action. Defaults to false. Useful to wait until the element is ready for the action without performing it.


click

Added in: v1.8 page.click
劝阻

请改用基于定位器的 locator.click()。了解有关 locators 的更多信息。

Use locator-based locator.click() instead. Read more about locators.

该方法通过执行以下步骤来点击匹配 selector 的元素:

This method clicks an element matching selector by performing the following steps:

  1. 查找与 selector 匹配的元素。如果没有,请等待,直到将匹配的元素附加到 DOM。

    Find an element matching selector. If there is none, wait until a matching element is attached to the DOM.

  2. 等待 actionability 检查匹配的元素,除非设置了 force 选项。如果在检查期间该元素被分离,则会重试整个操作。

    Wait for actionability checks on the matched element, unless force option is set. If the element is detached during the checks, the whole action is retried.

  3. 如果需要,将元素滚动到视图中。

    Scroll the element into view if needed.

  4. 使用 page.mouse 单击元素的中心,或指定的 position

    Use page.mouse to click in the center of the element, or the specified position.

  5. 等待启动的导航成功或失败,除非设置了 noWaitAfter 选项。

    Wait for initiated navigations to either succeed or fail, unless noWaitAfter option is set.

当所有组合步骤在指定的 timeout 时间内尚未完成时,此方法将抛出 TimeoutError。传递零超时会禁用此功能。

When all steps combined have not finished during the specified timeout, this method throws a TimeoutError. Passing zero timeout disables this.

用法

Usage

await page.click(selector);
await page.click(selector, options);

参数

Arguments

用于搜索元素的选择器。如果有多个元素满足选择器,则将使用第一个元素。

A selector to search for an element. If there are multiple elements satisfying the selector, the first will be used.

  • button "left"|"right"|"middle"(可选)#

    button "left"|"right"|"middle" (optional)#

    默认为 left

    Defaults to left.

默认为 1。参见 UIEvent.detail

defaults to 1. See UIEvent.detail.

mousedownmouseup 之间等待的时间(以毫秒为单位)。默认为 0。

Time to wait between mousedown and mouseup in milliseconds. Defaults to 0.

是否绕过 actionability 检查。默认为 false

Whether to bypass the actionability checks. Defaults to false.

  • modifiers Array<"Alt"|"Control"|"Meta"|"Shift"> (optional)#

要按下的修改键。确保在操作期间仅按下这些修饰符,然后恢复当前修饰符。如果未指定,则使用当前按下的修饰符。

Modifier keys to press. Ensures that only these modifiers are pressed during the operation, and then restores current modifiers back. If not specified, currently pressed modifiers are used.

启动导航的操作正在等待这些导航发生并开始加载页面。你可以通过设置此标志来选择不等待。仅在特殊情况下才需要此选项,例如导航到无法访问的页面。默认为 false

Actions that initiate navigations are waiting for these navigations to happen and for pages to start loading. You can opt out of waiting via setting this flag. You would only need this option in the exceptional cases such as navigating to inaccessible pages. Defaults to false.

相对于元素填充框左上角使用的点。如果未指定,则使用元素的一些可见点。

A point to use relative to the top-left corner of element padding box. If not specified, uses some visible point of the element.

  • strict boolean (optional) Added in: v1.14#

如果为 true,则调用需要选择器解析为单个元素。如果给定的选择器解析为多个元素,则调用会引发异常。

When true, the call requires selector to resolve to a single element. If given selector resolves to more than one element, the call throws an exception.

最长时间(以毫秒为单位)。默认为 0 - 没有超时。可以通过配置中的 actionTimeout 选项或使用 browserContext.setDefaultTimeout()page.setDefaultTimeout() 方法更改默认值。

Maximum time in milliseconds. Defaults to 0 - no timeout. The default value can be changed via actionTimeout option in the config, or by using the browserContext.setDefaultTimeout() or page.setDefaultTimeout() methods.

  • trial boolean (optional) Added in: v1.11#

设置后,此方法仅执行 actionability 检查并跳过该操作。默认为 false。等待元素准备好执行操作而不执行该操作很有用。

When set, this method only performs the actionability checks and skips the action. Defaults to false. Useful to wait until the element is ready for the action without performing it.


dblclick

Added in: v1.8 page.dblclick
劝阻

请改用基于定位器的 locator.dblclick()。了解有关 locators 的更多信息。

Use locator-based locator.dblclick() instead. Read more about locators.

该方法通过执行以下步骤双击与 selector 匹配的元素:

This method double clicks an element matching selector by performing the following steps:

  1. 查找与 selector 匹配的元素。如果没有,请等待,直到将匹配的元素附加到 DOM。

    Find an element matching selector. If there is none, wait until a matching element is attached to the DOM.

  2. 等待 actionability 检查匹配的元素,除非设置了 force 选项。如果在检查期间该元素被分离,则会重试整个操作。

    Wait for actionability checks on the matched element, unless force option is set. If the element is detached during the checks, the whole action is retried.

  3. 如果需要,将元素滚动到视图中。

    Scroll the element into view if needed.

  4. 使用 page.mouse 双击元素的中心,或指定的 position

    Use page.mouse to double click in the center of the element, or the specified position.

  5. 等待启动的导航成功或失败,除非设置了 noWaitAfter 选项。请注意,如果第一次点击 dblclick() 触发了导航事件,则此方法将抛出。

    Wait for initiated navigations to either succeed or fail, unless noWaitAfter option is set. Note that if the first click of the dblclick() triggers a navigation event, this method will throw.

当所有组合步骤在指定的 timeout 时间内尚未完成时,此方法将抛出 TimeoutError。传递零超时会禁用此功能。

When all steps combined have not finished during the specified timeout, this method throws a TimeoutError. Passing zero timeout disables this.

注意

page.dblclick() 调度两个 click 事件和一个 dblclick 事件。

page.dblclick() dispatches two click events and a single dblclick event.

用法

Usage

await page.dblclick(selector);
await page.dblclick(selector, options);

参数

Arguments

用于搜索元素的选择器。如果有多个元素满足选择器,则将使用第一个元素。

A selector to search for an element. If there are multiple elements satisfying the selector, the first will be used.

  • button "left"|"right"|"middle"(可选)#

    button "left"|"right"|"middle" (optional)#

    默认为 left

    Defaults to left.

mousedownmouseup 之间等待的时间(以毫秒为单位)。默认为 0。

Time to wait between mousedown and mouseup in milliseconds. Defaults to 0.

是否绕过 actionability 检查。默认为 false

Whether to bypass the actionability checks. Defaults to false.

  • modifiers Array<"Alt"|"Control"|"Meta"|"Shift"> (optional)#

要按下的修改键。确保在操作期间仅按下这些修饰符,然后恢复当前修饰符。如果未指定,则使用当前按下的修饰符。

Modifier keys to press. Ensures that only these modifiers are pressed during the operation, and then restores current modifiers back. If not specified, currently pressed modifiers are used.

启动导航的操作正在等待这些导航发生并开始加载页面。你可以通过设置此标志来选择不等待。仅在特殊情况下才需要此选项,例如导航到无法访问的页面。默认为 false

Actions that initiate navigations are waiting for these navigations to happen and for pages to start loading. You can opt out of waiting via setting this flag. You would only need this option in the exceptional cases such as navigating to inaccessible pages. Defaults to false.

相对于元素填充框左上角使用的点。如果未指定,则使用元素的一些可见点。

A point to use relative to the top-left corner of element padding box. If not specified, uses some visible point of the element.

  • strict boolean (optional) Added in: v1.14#

如果为 true,则调用需要选择器解析为单个元素。如果给定的选择器解析为多个元素,则调用会引发异常。

When true, the call requires selector to resolve to a single element. If given selector resolves to more than one element, the call throws an exception.

最长时间(以毫秒为单位)。默认为 0 - 没有超时。可以通过配置中的 actionTimeout 选项或使用 browserContext.setDefaultTimeout()page.setDefaultTimeout() 方法更改默认值。

Maximum time in milliseconds. Defaults to 0 - no timeout. The default value can be changed via actionTimeout option in the config, or by using the browserContext.setDefaultTimeout() or page.setDefaultTimeout() methods.

  • trial boolean (optional) Added in: v1.11#

设置后,此方法仅执行 actionability 检查并跳过该操作。默认为 false。等待元素准备好执行操作而不执行该操作很有用。

When set, this method only performs the actionability checks and skips the action. Defaults to false. Useful to wait until the element is ready for the action without performing it.


dispatchEvent

Added in: v1.8 page.dispatchEvent
劝阻

请改用基于定位器的 locator.dispatchEvent()。了解有关 locators 的更多信息。

Use locator-based locator.dispatchEvent() instead. Read more about locators.

下面的代码片段在元素上调度 click 事件。无论元素的可见性状态如何,都会调度 click。这相当于调用 element.click()

The snippet below dispatches the click event on the element. Regardless of the visibility state of the element, click is dispatched. This is equivalent to calling element.click().

用法

Usage

await page.dispatchEvent('button#submit', 'click');

在底层,它根据给定的 type 创建事件的实例,使用 eventInit 属性对其进行初始化,并将其分派到元素上。事件默认为 composedcancelable 和 bubble。

Under the hood, it creates an instance of an event based on the given type, initializes it with eventInit properties and dispatches it on the element. Events are composed, cancelable and bubble by default.

由于 eventInit 是特定于事件的,因此请参阅事件文档以获取初始属性列表:

Since eventInit is event-specific, please refer to the events documentation for the lists of initial properties:

如果你希望将活动对象传递到事件中,你还可以指定 JSHandle 作为属性值:

You can also specify JSHandle as the property value if you want live objects to be passed into the event:

// Note you can only create DataTransfer in Chromium and Firefox
const dataTransfer = await page.evaluateHandle(() => new DataTransfer());
await page.dispatchEvent('#source', 'dragstart', { dataTransfer });

参数

Arguments

用于搜索元素的选择器。如果有多个元素满足选择器,则将使用第一个元素。

A selector to search for an element. If there are multiple elements satisfying the selector, the first will be used.

DOM 事件类型:"click""dragstart"

DOM event type: "click", "dragstart", etc.

可选的特定于事件的初始化属性。

Optional event-specific initialization properties.

  • options Object (optional)

    • strict boolean (optional) Added in: v1.14#

如果为 true,则调用需要选择器解析为单个元素。如果给定的选择器解析为多个元素,则调用会引发异常。

When true, the call requires selector to resolve to a single element. If given selector resolves to more than one element, the call throws an exception.

最长时间(以毫秒为单位)。默认为 0 - 没有超时。可以通过配置中的 actionTimeout 选项或使用 browserContext.setDefaultTimeout()page.setDefaultTimeout() 方法更改默认值。

Maximum time in milliseconds. Defaults to 0 - no timeout. The default value can be changed via actionTimeout option in the config, or by using the browserContext.setDefaultTimeout() or page.setDefaultTimeout() methods.


fill

Added in: v1.8 page.fill
劝阻

请改用基于定位器的 locator.fill()。了解有关 locators 的更多信息。

Use locator-based locator.fill() instead. Read more about locators.

该方法等待匹配 selector 的元素,等待 actionability 检查,聚焦该元素,填充它并在填充后触发 input 事件。请注意,你可以传递空字符串来清除输入字段。

This method waits for an element matching selector, waits for actionability checks, focuses the element, fills it and triggers an input event after filling. Note that you can pass an empty string to clear the input field.

如果目标元素不是 <input><textarea>[contenteditable] 元素,则此方法将引发错误。但是,如果该元素位于具有关联的 control<label> 元素内部,则该控件将被填充。

If the target element is not an <input>, <textarea> or [contenteditable] element, this method throws an error. However, if the element is inside the <label> element that has an associated control, the control will be filled instead.

要发送细粒度键盘事件,请使用 locator.pressSequentially()

To send fine-grained keyboard events, use locator.pressSequentially().

用法

Usage

await page.fill(selector, value);
await page.fill(selector, value, options);

参数

Arguments

用于搜索元素的选择器。如果有多个元素满足选择器,则将使用第一个元素。

A selector to search for an element. If there are multiple elements satisfying the selector, the first will be used.

要填充 <input><textarea>[contenteditable] 元素的值。

Value to fill for the <input>, <textarea> or [contenteditable] element.

是否绕过 actionability 检查。默认为 false

Whether to bypass the actionability checks. Defaults to false.

启动导航的操作正在等待这些导航发生并开始加载页面。你可以通过设置此标志来选择不等待。仅在特殊情况下才需要此选项,例如导航到无法访问的页面。默认为 false

Actions that initiate navigations are waiting for these navigations to happen and for pages to start loading. You can opt out of waiting via setting this flag. You would only need this option in the exceptional cases such as navigating to inaccessible pages. Defaults to false.

  • strict boolean (optional) Added in: v1.14#

如果为 true,则调用需要选择器解析为单个元素。如果给定的选择器解析为多个元素,则调用会引发异常。

When true, the call requires selector to resolve to a single element. If given selector resolves to more than one element, the call throws an exception.

最长时间(以毫秒为单位)。默认为 0 - 没有超时。可以通过配置中的 actionTimeout 选项或使用 browserContext.setDefaultTimeout()page.setDefaultTimeout() 方法更改默认值。

Maximum time in milliseconds. Defaults to 0 - no timeout. The default value can be changed via actionTimeout option in the config, or by using the browserContext.setDefaultTimeout() or page.setDefaultTimeout() methods.


focus

Added in: v1.8 page.focus
劝阻

请改用基于定位器的 locator.focus()。了解有关 locators 的更多信息。

Use locator-based locator.focus() instead. Read more about locators.

此方法获取带有 selector 的元素并聚焦它。如果没有与 selector 匹配的元素,该方法将等待,直到 DOM 中出现匹配的元素。

This method fetches an element with selector and focuses it. If there's no element matching selector, the method waits until a matching element appears in the DOM.

用法

Usage

await page.focus(selector);
await page.focus(selector, options);

参数

Arguments

用于搜索元素的选择器。如果有多个元素满足选择器,则将使用第一个元素。

A selector to search for an element. If there are multiple elements satisfying the selector, the first will be used.

  • options Object (optional)

    • strict boolean (optional) Added in: v1.14#

如果为 true,则调用需要选择器解析为单个元素。如果给定的选择器解析为多个元素,则调用会引发异常。

When true, the call requires selector to resolve to a single element. If given selector resolves to more than one element, the call throws an exception.

最长时间(以毫秒为单位)。默认为 0 - 没有超时。可以通过配置中的 actionTimeout 选项或使用 browserContext.setDefaultTimeout()page.setDefaultTimeout() 方法更改默认值。

Maximum time in milliseconds. Defaults to 0 - no timeout. The default value can be changed via actionTimeout option in the config, or by using the browserContext.setDefaultTimeout() or page.setDefaultTimeout() methods.


getAttribute

Added in: v1.8 page.getAttribute
劝阻

请改用基于定位器的 locator.getAttribute()。了解有关 locators 的更多信息。

Use locator-based locator.getAttribute() instead. Read more about locators.

返回元素属性值。

Returns element attribute value.

用法

Usage

await page.getAttribute(selector, name);
await page.getAttribute(selector, name, options);

参数

Arguments

用于搜索元素的选择器。如果有多个元素满足选择器,则将使用第一个元素。

A selector to search for an element. If there are multiple elements satisfying the selector, the first will be used.

要获取其值的属性名称。

Attribute name to get the value for.

  • options Object (optional)

    • strict boolean (optional) Added in: v1.14#

如果为 true,则调用需要选择器解析为单个元素。如果给定的选择器解析为多个元素,则调用会引发异常。

When true, the call requires selector to resolve to a single element. If given selector resolves to more than one element, the call throws an exception.

最长时间(以毫秒为单位)。默认为 0 - 没有超时。可以通过配置中的 actionTimeout 选项或使用 browserContext.setDefaultTimeout()page.setDefaultTimeout() 方法更改默认值。

Maximum time in milliseconds. Defaults to 0 - no timeout. The default value can be changed via actionTimeout option in the config, or by using the browserContext.setDefaultTimeout() or page.setDefaultTimeout() methods.

返回

Returns


hover

Added in: v1.8 page.hover
劝阻

请改用基于定位器的 locator.hover()。了解有关 locators 的更多信息。

Use locator-based locator.hover() instead. Read more about locators.

该方法通过执行以下步骤将鼠标悬停在与 selector 匹配的元素上:

This method hovers over an element matching selector by performing the following steps:

  1. 查找与 selector 匹配的元素。如果没有,请等待,直到将匹配的元素附加到 DOM。

    Find an element matching selector. If there is none, wait until a matching element is attached to the DOM.

  2. 等待 actionability 检查匹配的元素,除非设置了 force 选项。如果在检查期间该元素被分离,则会重试整个操作。

    Wait for actionability checks on the matched element, unless force option is set. If the element is detached during the checks, the whole action is retried.

  3. 如果需要,将元素滚动到视图中。

    Scroll the element into view if needed.

  4. 使用 page.mouse 将鼠标悬停在元素的中心或指定的 position 上。

    Use page.mouse to hover over the center of the element, or the specified position.

  5. 等待启动的导航成功或失败,除非设置了 noWaitAfter 选项。

    Wait for initiated navigations to either succeed or fail, unless noWaitAfter option is set.

当所有组合步骤在指定的 timeout 时间内尚未完成时,此方法将抛出 TimeoutError。传递零超时会禁用此功能。

When all steps combined have not finished during the specified timeout, this method throws a TimeoutError. Passing zero timeout disables this.

用法

Usage

await page.hover(selector);
await page.hover(selector, options);

参数

Arguments

用于搜索元素的选择器。如果有多个元素满足选择器,则将使用第一个元素。

A selector to search for an element. If there are multiple elements satisfying the selector, the first will be used.

是否绕过 actionability 检查。默认为 false

Whether to bypass the actionability checks. Defaults to false.

  • modifiers Array<"Alt"|"Control"|"Meta"|"Shift"> (optional)#

要按下的修改键。确保在操作期间仅按下这些修饰符,然后恢复当前修饰符。如果未指定,则使用当前按下的修饰符。

Modifier keys to press. Ensures that only these modifiers are pressed during the operation, and then restores current modifiers back. If not specified, currently pressed modifiers are used.

  • noWaitAfter boolean (optional) Added in: v1.28#

启动导航的操作正在等待这些导航发生并开始加载页面。你可以通过设置此标志来选择不等待。仅在特殊情况下才需要此选项,例如导航到无法访问的页面。默认为 false

Actions that initiate navigations are waiting for these navigations to happen and for pages to start loading. You can opt out of waiting via setting this flag. You would only need this option in the exceptional cases such as navigating to inaccessible pages. Defaults to false.

相对于元素填充框左上角使用的点。如果未指定,则使用元素的一些可见点。

A point to use relative to the top-left corner of element padding box. If not specified, uses some visible point of the element.

  • strict boolean (optional) Added in: v1.14#

如果为 true,则调用需要选择器解析为单个元素。如果给定的选择器解析为多个元素,则调用会引发异常。

When true, the call requires selector to resolve to a single element. If given selector resolves to more than one element, the call throws an exception.

最长时间(以毫秒为单位)。默认为 0 - 没有超时。可以通过配置中的 actionTimeout 选项或使用 browserContext.setDefaultTimeout()page.setDefaultTimeout() 方法更改默认值。

Maximum time in milliseconds. Defaults to 0 - no timeout. The default value can be changed via actionTimeout option in the config, or by using the browserContext.setDefaultTimeout() or page.setDefaultTimeout() methods.

  • trial boolean (optional) Added in: v1.11#

设置后,此方法仅执行 actionability 检查并跳过该操作。默认为 false。等待元素准备好执行操作而不执行该操作很有用。

When set, this method only performs the actionability checks and skips the action. Defaults to false. Useful to wait until the element is ready for the action without performing it.


innerHTML

Added in: v1.8 page.innerHTML
劝阻

请改用基于定位器的 locator.innerHTML()。了解有关 locators 的更多信息。

Use locator-based locator.innerHTML() instead. Read more about locators.

返回 element.innerHTML

Returns element.innerHTML.

用法

Usage

await page.innerHTML(selector);
await page.innerHTML(selector, options);

参数

Arguments

用于搜索元素的选择器。如果有多个元素满足选择器,则将使用第一个元素。

A selector to search for an element. If there are multiple elements satisfying the selector, the first will be used.

  • options Object (optional)

    • strict boolean (optional) Added in: v1.14#

如果为 true,则调用需要选择器解析为单个元素。如果给定的选择器解析为多个元素,则调用会引发异常。

When true, the call requires selector to resolve to a single element. If given selector resolves to more than one element, the call throws an exception.

最长时间(以毫秒为单位)。默认为 0 - 没有超时。可以通过配置中的 actionTimeout 选项或使用 browserContext.setDefaultTimeout()page.setDefaultTimeout() 方法更改默认值。

Maximum time in milliseconds. Defaults to 0 - no timeout. The default value can be changed via actionTimeout option in the config, or by using the browserContext.setDefaultTimeout() or page.setDefaultTimeout() methods.

返回

Returns


innerText

Added in: v1.8 page.innerText
劝阻

请改用基于定位器的 locator.innerText()。了解有关 locators 的更多信息。

Use locator-based locator.innerText() instead. Read more about locators.

返回 element.innerText

Returns element.innerText.

用法

Usage

await page.innerText(selector);
await page.innerText(selector, options);

参数

Arguments

用于搜索元素的选择器。如果有多个元素满足选择器,则将使用第一个元素。

A selector to search for an element. If there are multiple elements satisfying the selector, the first will be used.

  • options Object (optional)

    • strict boolean (optional) Added in: v1.14#

如果为 true,则调用需要选择器解析为单个元素。如果给定的选择器解析为多个元素,则调用会引发异常。

When true, the call requires selector to resolve to a single element. If given selector resolves to more than one element, the call throws an exception.

最长时间(以毫秒为单位)。默认为 0 - 没有超时。可以通过配置中的 actionTimeout 选项或使用 browserContext.setDefaultTimeout()page.setDefaultTimeout() 方法更改默认值。

Maximum time in milliseconds. Defaults to 0 - no timeout. The default value can be changed via actionTimeout option in the config, or by using the browserContext.setDefaultTimeout() or page.setDefaultTimeout() methods.

返回

Returns


inputValue

Added in: v1.13 page.inputValue
劝阻

请改用基于定位器的 locator.inputValue()。了解有关 locators 的更多信息。

Use locator-based locator.inputValue() instead. Read more about locators.

返回所选 <input><textarea><select> 元素的 input.value

Returns input.value for the selected <input> or <textarea> or <select> element.

抛出非输入元素。但是,如果该元素位于具有关联的 control<label> 元素内部,则返回控件的值。

Throws for non-input elements. However, if the element is inside the <label> element that has an associated control, returns the value of the control.

用法

Usage

await page.inputValue(selector);
await page.inputValue(selector, options);

参数

Arguments

用于搜索元素的选择器。如果有多个元素满足选择器,则将使用第一个元素。

A selector to search for an element. If there are multiple elements satisfying the selector, the first will be used.

  • options Object (optional)

    • strict boolean (optional) Added in: v1.14#

如果为 true,则调用需要选择器解析为单个元素。如果给定的选择器解析为多个元素,则调用会引发异常。

When true, the call requires selector to resolve to a single element. If given selector resolves to more than one element, the call throws an exception.

最长时间(以毫秒为单位)。默认为 0 - 没有超时。可以通过配置中的 actionTimeout 选项或使用 browserContext.setDefaultTimeout()page.setDefaultTimeout() 方法更改默认值。

Maximum time in milliseconds. Defaults to 0 - no timeout. The default value can be changed via actionTimeout option in the config, or by using the browserContext.setDefaultTimeout() or page.setDefaultTimeout() methods.

返回

Returns


isChecked

Added in: v1.8 page.isChecked
劝阻

请改用基于定位器的 locator.isChecked()。了解有关 locators 的更多信息。

Use locator-based locator.isChecked() instead. Read more about locators.

返回该元素是否被检查。如果元素不是复选框或单选输入,则抛出此异常。

Returns whether the element is checked. Throws if the element is not a checkbox or radio input.

用法

Usage

await page.isChecked(selector);
await page.isChecked(selector, options);

参数

Arguments

用于搜索元素的选择器。如果有多个元素满足选择器,则将使用第一个元素。

A selector to search for an element. If there are multiple elements satisfying the selector, the first will be used.

  • options Object (optional)

    • strict boolean (optional) Added in: v1.14#

如果为 true,则调用需要选择器解析为单个元素。如果给定的选择器解析为多个元素,则调用会引发异常。

When true, the call requires selector to resolve to a single element. If given selector resolves to more than one element, the call throws an exception.

最长时间(以毫秒为单位)。默认为 0 - 没有超时。可以通过配置中的 actionTimeout 选项或使用 browserContext.setDefaultTimeout()page.setDefaultTimeout() 方法更改默认值。

Maximum time in milliseconds. Defaults to 0 - no timeout. The default value can be changed via actionTimeout option in the config, or by using the browserContext.setDefaultTimeout() or page.setDefaultTimeout() methods.

返回

Returns


isDisabled

Added in: v1.8 page.isDisabled
劝阻

请改用基于定位器的 locator.isDisabled()。了解有关 locators 的更多信息。

Use locator-based locator.isDisabled() instead. Read more about locators.

返回该元素是否被禁用,与 enabled 相反。

Returns whether the element is disabled, the opposite of enabled.

用法

Usage

await page.isDisabled(selector);
await page.isDisabled(selector, options);

参数

Arguments

用于搜索元素的选择器。如果有多个元素满足选择器,则将使用第一个元素。

A selector to search for an element. If there are multiple elements satisfying the selector, the first will be used.

  • options Object (optional)

    • strict boolean (optional) Added in: v1.14#

如果为 true,则调用需要选择器解析为单个元素。如果给定的选择器解析为多个元素,则调用会引发异常。

When true, the call requires selector to resolve to a single element. If given selector resolves to more than one element, the call throws an exception.

最长时间(以毫秒为单位)。默认为 0 - 没有超时。可以通过配置中的 actionTimeout 选项或使用 browserContext.setDefaultTimeout()page.setDefaultTimeout() 方法更改默认值。

Maximum time in milliseconds. Defaults to 0 - no timeout. The default value can be changed via actionTimeout option in the config, or by using the browserContext.setDefaultTimeout() or page.setDefaultTimeout() methods.

返回

Returns


isEditable

Added in: v1.8 page.isEditable
劝阻

请改用基于定位器的 locator.isEditable()。了解有关 locators 的更多信息。

Use locator-based locator.isEditable() instead. Read more about locators.

返回元素是否为 editable

Returns whether the element is editable.

用法

Usage

await page.isEditable(selector);
await page.isEditable(selector, options);

参数

Arguments

用于搜索元素的选择器。如果有多个元素满足选择器,则将使用第一个元素。

A selector to search for an element. If there are multiple elements satisfying the selector, the first will be used.

  • options Object (optional)

    • strict boolean (optional) Added in: v1.14#

如果为 true,则调用需要选择器解析为单个元素。如果给定的选择器解析为多个元素,则调用会引发异常。

When true, the call requires selector to resolve to a single element. If given selector resolves to more than one element, the call throws an exception.

最长时间(以毫秒为单位)。默认为 0 - 没有超时。可以通过配置中的 actionTimeout 选项或使用 browserContext.setDefaultTimeout()page.setDefaultTimeout() 方法更改默认值。

Maximum time in milliseconds. Defaults to 0 - no timeout. The default value can be changed via actionTimeout option in the config, or by using the browserContext.setDefaultTimeout() or page.setDefaultTimeout() methods.

返回

Returns


isEnabled

Added in: v1.8 page.isEnabled
劝阻

请改用基于定位器的 locator.isEnabled()。了解有关 locators 的更多信息。

Use locator-based locator.isEnabled() instead. Read more about locators.

返回元素是否为 enabled

Returns whether the element is enabled.

用法

Usage

await page.isEnabled(selector);
await page.isEnabled(selector, options);

参数

Arguments

用于搜索元素的选择器。如果有多个元素满足选择器,则将使用第一个元素。

A selector to search for an element. If there are multiple elements satisfying the selector, the first will be used.

  • options Object (optional)

    • strict boolean (optional) Added in: v1.14#

如果为 true,则调用需要选择器解析为单个元素。如果给定的选择器解析为多个元素,则调用会引发异常。

When true, the call requires selector to resolve to a single element. If given selector resolves to more than one element, the call throws an exception.

最长时间(以毫秒为单位)。默认为 0 - 没有超时。可以通过配置中的 actionTimeout 选项或使用 browserContext.setDefaultTimeout()page.setDefaultTimeout() 方法更改默认值。

Maximum time in milliseconds. Defaults to 0 - no timeout. The default value can be changed via actionTimeout option in the config, or by using the browserContext.setDefaultTimeout() or page.setDefaultTimeout() methods.

返回

Returns


isHidden

Added in: v1.8 page.isHidden
劝阻

请改用基于定位器的 locator.isHidden()。了解有关 locators 的更多信息。

Use locator-based locator.isHidden() instead. Read more about locators.

返回元素是否隐藏,与 visible 相反。不匹配任何元素的 selector 被视为隐藏。

Returns whether the element is hidden, the opposite of visible. selector that does not match any elements is considered hidden.

用法

Usage

await page.isHidden(selector);
await page.isHidden(selector, options);

参数

Arguments

用于搜索元素的选择器。如果有多个元素满足选择器,则将使用第一个元素。

A selector to search for an element. If there are multiple elements satisfying the selector, the first will be used.

  • options Object (optional)

    • strict boolean (optional) Added in: v1.14#

如果为 true,则调用需要选择器解析为单个元素。如果给定的选择器解析为多个元素,则调用会引发异常。

When true, the call requires selector to resolve to a single element. If given selector resolves to more than one element, the call throws an exception.

Deprecated

This option is ignored. page.isHidden() does not wait for the element to become hidden and returns immediately.

返回

Returns


isVisible

Added in: v1.8 page.isVisible
劝阻

请改用基于定位器的 locator.isVisible()。了解有关 locators 的更多信息。

Use locator-based locator.isVisible() instead. Read more about locators.

返回元素是否为 visible。不匹配任何元素的 selector 被视为不可见。

Returns whether the element is visible. selector that does not match any elements is considered not visible.

用法

Usage

await page.isVisible(selector);
await page.isVisible(selector, options);

参数

Arguments

用于搜索元素的选择器。如果有多个元素满足选择器,则将使用第一个元素。

A selector to search for an element. If there are multiple elements satisfying the selector, the first will be used.

  • options Object (optional)

    • strict boolean (optional) Added in: v1.14#

如果为 true,则调用需要选择器解析为单个元素。如果给定的选择器解析为多个元素,则调用会引发异常。

When true, the call requires selector to resolve to a single element. If given selector resolves to more than one element, the call throws an exception.

Deprecated

This option is ignored. page.isVisible() does not wait for the element to become visible and returns immediately.

返回

Returns


press

Added in: v1.8 page.press
劝阻

请改用基于定位器的 locator.press()。了解有关 locators 的更多信息。

Use locator-based locator.press() instead. Read more about locators.

聚焦元素,然后使用 keyboard.down()keyboard.up()

Focuses the element, and then uses keyboard.down() and keyboard.up().

key 可以指定预期的 keyboardEvent.key 值或单个字符来生成文本。可以找到 key 值的超集 此处。键的示例有:

key can specify the intended keyboardEvent.key value or a single character to generate the text for. A superset of the key values can be found here. Examples of the keys are:

F1 - F12Digit0-Digit9KeyA-KeyZBackquoteMinusEqualBackslashBackspaceTabDeleteEscapeArrowDownEndEnterHomeInsertPageDownPageUpArrowRightArrowUp 等。

F1 - F12, Digit0- Digit9, KeyA- KeyZ, Backquote, Minus, Equal, Backslash, Backspace, Tab, Delete, Escape, ArrowDown, End, Enter, Home, Insert, PageDown, PageUp, ArrowRight, ArrowUp, etc.

还支持以下修改快捷方式:ShiftControlAltMetaShiftLeft

Following modification shortcuts are also supported: Shift, Control, Alt, Meta, ShiftLeft.

按住 Shift 将键入与大写 key 相对应的文本。

Holding down Shift will type the text that corresponds to the key in the upper case.

如果 key 是单个字符,则区分大小写,因此值 aA 将生成各自不同的文本。

If key is a single character, it is case-sensitive, so the values a and A will generate different respective texts.

还支持 key: "Control+o"key: "Control+Shift+T" 等快捷方式。当使用修饰符指定时,修饰符将被按下并在按下后续键的同时保持不变。

Shortcuts such as key: "Control+o" or key: "Control+Shift+T" are supported as well. When specified with the modifier, modifier is pressed and being held while the subsequent key is being pressed.

用法

Usage

const page = await browser.newPage();
await page.goto('https://keycode.info');
await page.press('body', 'A');
await page.screenshot({ path: 'A.png' });
await page.press('body', 'ArrowLeft');
await page.screenshot({ path: 'ArrowLeft.png' });
await page.press('body', 'Shift+O');
await page.screenshot({ path: 'O.png' });
await browser.close();

参数

Arguments

用于搜索元素的选择器。如果有多个元素满足选择器,则将使用第一个元素。

A selector to search for an element. If there are multiple elements satisfying the selector, the first will be used.

要按下的键的名称或要生成的字符,例如 ArrowLefta

Name of the key to press or a character to generate, such as ArrowLeft or a.

keydownkeyup 之间等待的时间(以毫秒为单位)。默认为 0。

Time to wait between keydown and keyup in milliseconds. Defaults to 0.

启动导航的操作正在等待这些导航发生并开始加载页面。你可以通过设置此标志来选择不等待。仅在特殊情况下才需要此选项,例如导航到无法访问的页面。默认为 false

Actions that initiate navigations are waiting for these navigations to happen and for pages to start loading. You can opt out of waiting via setting this flag. You would only need this option in the exceptional cases such as navigating to inaccessible pages. Defaults to false.

  • strict boolean (optional) Added in: v1.14#

如果为 true,则调用需要选择器解析为单个元素。如果给定的选择器解析为多个元素,则调用会引发异常。

When true, the call requires selector to resolve to a single element. If given selector resolves to more than one element, the call throws an exception.

最长时间(以毫秒为单位)。默认为 0 - 没有超时。可以通过配置中的 actionTimeout 选项或使用 browserContext.setDefaultTimeout()page.setDefaultTimeout() 方法更改默认值。

Maximum time in milliseconds. Defaults to 0 - no timeout. The default value can be changed via actionTimeout option in the config, or by using the browserContext.setDefaultTimeout() or page.setDefaultTimeout() methods.


selectOption

Added in: v1.8 page.selectOption
劝阻

请改用基于定位器的 locator.selectOption()。了解有关 locators 的更多信息。

Use locator-based locator.selectOption() instead. Read more about locators.

此方法等待与 selector 匹配的元素,等待 actionability 检查,等待所有指定的选项都出现在 <select> 元素中并选择这些选项。

This method waits for an element matching selector, waits for actionability checks, waits until all specified options are present in the <select> element and selects these options.

如果目标元素不是 <select> 元素,则此方法将引发错误。但是,如果该元素位于具有关联的 control<label> 元素内部,则将改用该控件。

If the target element is not a <select> element, this method throws an error. However, if the element is inside the <label> element that has an associated control, the control will be used instead.

返回已成功选择的选项值的数组。

Returns the array of option values that have been successfully selected.

选择所有提供的选项后,触发 changeinput 事件。

Triggers a change and input event once all the provided options have been selected.

用法

Usage

// Single selection matching the value or label
page.selectOption('select#colors', 'blue');

// single selection matching the label
page.selectOption('select#colors', { label: 'Blue' });

// multiple selection
page.selectOption('select#colors', ['red', 'green', 'blue']);

参数

Arguments

用于搜索元素的选择器。如果有多个元素满足选择器,则将使用第一个元素。

A selector to search for an element. If there are multiple elements satisfying the selector, the first will be used.

option.value 的比赛。可选的。

Matches by option.value. Optional.

option.label 的比赛。可选的。

Matches by option.label. Optional.

按索引匹配。可选的。

Matches by the index. Optional.

可供选择的选项。如果 <select> 具有 multiple 属性,则选择所有匹配选项,否则仅选择与传递的选项之一匹配的第一个选项。字符串值与值和标签相匹配。如果所有指定的属性都匹配,则选项被视为匹配。

Options to select. If the <select> has the multiple attribute, all matching options are selected, otherwise only the first option matching one of the passed options is selected. String values are matching both values and labels. Option is considered matching if all specified properties match.

是否绕过 actionability 检查。默认为 false

Whether to bypass the actionability checks. Defaults to false.

启动导航的操作正在等待这些导航发生并开始加载页面。你可以通过设置此标志来选择不等待。仅在特殊情况下才需要此选项,例如导航到无法访问的页面。默认为 false

Actions that initiate navigations are waiting for these navigations to happen and for pages to start loading. You can opt out of waiting via setting this flag. You would only need this option in the exceptional cases such as navigating to inaccessible pages. Defaults to false.

  • strict boolean (optional) Added in: v1.14#

如果为 true,则调用需要选择器解析为单个元素。如果给定的选择器解析为多个元素,则调用会引发异常。

When true, the call requires selector to resolve to a single element. If given selector resolves to more than one element, the call throws an exception.

最长时间(以毫秒为单位)。默认为 0 - 没有超时。可以通过配置中的 actionTimeout 选项或使用 browserContext.setDefaultTimeout()page.setDefaultTimeout() 方法更改默认值。

Maximum time in milliseconds. Defaults to 0 - no timeout. The default value can be changed via actionTimeout option in the config, or by using the browserContext.setDefaultTimeout() or page.setDefaultTimeout() methods.

返回

Returns


setChecked

Added in: v1.15 page.setChecked
劝阻

请改用基于定位器的 locator.setChecked()。了解有关 locators 的更多信息。

Use locator-based locator.setChecked() instead. Read more about locators.

该方法通过执行以下步骤来检查或取消选中与 selector 匹配的元素:

This method checks or unchecks an element matching selector by performing the following steps:

  1. 查找与 selector 匹配的元素。如果没有,请等待,直到将匹配的元素附加到 DOM。

    Find an element matching selector. If there is none, wait until a matching element is attached to the DOM.

  2. 确保匹配的元素是复选框或单选输入。如果不是,该方法将抛出异常。

    Ensure that matched element is a checkbox or a radio input. If not, this method throws.

  3. 如果元素已经具有正确的检查状态,则此方法立即返回。

    If the element already has the right checked state, this method returns immediately.

  4. 等待 actionability 检查匹配的元素,除非设置了 force 选项。如果在检查期间该元素被分离,则会重试整个操作。

    Wait for actionability checks on the matched element, unless force option is set. If the element is detached during the checks, the whole action is retried.

  5. 如果需要,将元素滚动到视图中。

    Scroll the element into view if needed.

  6. 使用 page.mouse 单击元素的中心。

    Use page.mouse to click in the center of the element.

  7. 等待启动的导航成功或失败,除非设置了 noWaitAfter 选项。

    Wait for initiated navigations to either succeed or fail, unless noWaitAfter option is set.

  8. 确保该元素现在已选中或取消选中。如果不是,该方法将抛出异常。

    Ensure that the element is now checked or unchecked. If not, this method throws.

当所有组合步骤在指定的 timeout 时间内尚未完成时,此方法将抛出 TimeoutError。传递零超时会禁用此功能。

When all steps combined have not finished during the specified timeout, this method throws a TimeoutError. Passing zero timeout disables this.

用法

Usage

await page.setChecked(selector, checked);
await page.setChecked(selector, checked, options);

参数

Arguments

用于搜索元素的选择器。如果有多个元素满足选择器,则将使用第一个元素。

A selector to search for an element. If there are multiple elements satisfying the selector, the first will be used.

是否选中或取消选中复选框。

Whether to check or uncheck the checkbox.

是否绕过 actionability 检查。默认为 false

Whether to bypass the actionability checks. Defaults to false.

启动导航的操作正在等待这些导航发生并开始加载页面。你可以通过设置此标志来选择不等待。仅在特殊情况下才需要此选项,例如导航到无法访问的页面。默认为 false

Actions that initiate navigations are waiting for these navigations to happen and for pages to start loading. You can opt out of waiting via setting this flag. You would only need this option in the exceptional cases such as navigating to inaccessible pages. Defaults to false.

相对于元素填充框左上角使用的点。如果未指定,则使用元素的一些可见点。

A point to use relative to the top-left corner of element padding box. If not specified, uses some visible point of the element.

如果为 true,则调用需要选择器解析为单个元素。如果给定的选择器解析为多个元素,则调用会引发异常。

When true, the call requires selector to resolve to a single element. If given selector resolves to more than one element, the call throws an exception.

最长时间(以毫秒为单位)。默认为 0 - 没有超时。可以通过配置中的 actionTimeout 选项或使用 browserContext.setDefaultTimeout()page.setDefaultTimeout() 方法更改默认值。

Maximum time in milliseconds. Defaults to 0 - no timeout. The default value can be changed via actionTimeout option in the config, or by using the browserContext.setDefaultTimeout() or page.setDefaultTimeout() methods.

设置后,此方法仅执行 actionability 检查并跳过该操作。默认为 false。等待元素准备好执行操作而不执行该操作很有用。

When set, this method only performs the actionability checks and skips the action. Defaults to false. Useful to wait until the element is ready for the action without performing it.


setInputFiles

Added in: v1.8 page.setInputFiles
劝阻

请改用基于定位器的 locator.setInputFiles()。了解有关 locators 的更多信息。

Use locator-based locator.setInputFiles() instead. Read more about locators.

将文件输入的值设置为这些文件路径或文件。如果某些 filePaths 是相对路径,则它们将相对于当前工作目录进行解析。对于空数组,清除选定的文件。

Sets the value of the file input to these file paths or files. If some of the filePaths are relative paths, then they are resolved relative to the current working directory. For empty array, clears the selected files.

此方法期望 selector 指向 输入元素。但是,如果该元素位于具有关联的 control<label> 元素内,则改为以控件为目标。

This method expects selector to point to an input element. However, if the element is inside the <label> element that has an associated control, targets the control instead.

用法

Usage

await page.setInputFiles(selector, files);
await page.setInputFiles(selector, files, options);

参数

Arguments

用于搜索元素的选择器。如果有多个元素满足选择器,则将使用第一个元素。

A selector to search for an element. If there are multiple elements satisfying the selector, the first will be used.

文件名

File name

文件类型

File type

文件内容

File content

启动导航的操作正在等待这些导航发生并开始加载页面。你可以通过设置此标志来选择不等待。仅在特殊情况下才需要此选项,例如导航到无法访问的页面。默认为 false

Actions that initiate navigations are waiting for these navigations to happen and for pages to start loading. You can opt out of waiting via setting this flag. You would only need this option in the exceptional cases such as navigating to inaccessible pages. Defaults to false.

  • strict boolean (optional) Added in: v1.14#

如果为 true,则调用需要选择器解析为单个元素。如果给定的选择器解析为多个元素,则调用会引发异常。

When true, the call requires selector to resolve to a single element. If given selector resolves to more than one element, the call throws an exception.

最长时间(以毫秒为单位)。默认为 0 - 没有超时。可以通过配置中的 actionTimeout 选项或使用 browserContext.setDefaultTimeout()page.setDefaultTimeout() 方法更改默认值。

Maximum time in milliseconds. Defaults to 0 - no timeout. The default value can be changed via actionTimeout option in the config, or by using the browserContext.setDefaultTimeout() or page.setDefaultTimeout() methods.


tap

Added in: v1.8 page.tap
劝阻

请改用基于定位器的 locator.tap()。了解有关 locators 的更多信息。

Use locator-based locator.tap() instead. Read more about locators.

该方法通过执行以下步骤来点击匹配 selector 的元素:

This method taps an element matching selector by performing the following steps:

  1. 查找与 selector 匹配的元素。如果没有,请等待,直到将匹配的元素附加到 DOM。

    Find an element matching selector. If there is none, wait until a matching element is attached to the DOM.

  2. 等待 actionability 检查匹配的元素,除非设置了 force 选项。如果在检查期间该元素被分离,则会重试整个操作。

    Wait for actionability checks on the matched element, unless force option is set. If the element is detached during the checks, the whole action is retried.

  3. 如果需要,将元素滚动到视图中。

    Scroll the element into view if needed.

  4. 使用 page.touchscreen 点击元素的中心,或指定的 position

    Use page.touchscreen to tap the center of the element, or the specified position.

  5. 等待启动的导航成功或失败,除非设置了 noWaitAfter 选项。

    Wait for initiated navigations to either succeed or fail, unless noWaitAfter option is set.

当所有组合步骤在指定的 timeout 时间内尚未完成时,此方法将抛出 TimeoutError。传递零超时会禁用此功能。

When all steps combined have not finished during the specified timeout, this method throws a TimeoutError. Passing zero timeout disables this.

注意

如果浏览器上下文的 hasTouch 选项为 false,则 page.tap() 该方法将抛出异常。

page.tap() the method will throw if hasTouch option of the browser context is false.

用法

Usage

await page.tap(selector);
await page.tap(selector, options);

参数

Arguments

用于搜索元素的选择器。如果有多个元素满足选择器,则将使用第一个元素。

A selector to search for an element. If there are multiple elements satisfying the selector, the first will be used.

是否绕过 actionability 检查。默认为 false

Whether to bypass the actionability checks. Defaults to false.

  • modifiers Array<"Alt"|"Control"|"Meta"|"Shift"> (optional)#

要按下的修改键。确保在操作期间仅按下这些修饰符,然后恢复当前修饰符。如果未指定,则使用当前按下的修饰符。

Modifier keys to press. Ensures that only these modifiers are pressed during the operation, and then restores current modifiers back. If not specified, currently pressed modifiers are used.

启动导航的操作正在等待这些导航发生并开始加载页面。你可以通过设置此标志来选择不等待。仅在特殊情况下才需要此选项,例如导航到无法访问的页面。默认为 false

Actions that initiate navigations are waiting for these navigations to happen and for pages to start loading. You can opt out of waiting via setting this flag. You would only need this option in the exceptional cases such as navigating to inaccessible pages. Defaults to false.

相对于元素填充框左上角使用的点。如果未指定,则使用元素的一些可见点。

A point to use relative to the top-left corner of element padding box. If not specified, uses some visible point of the element.

  • strict boolean (optional) Added in: v1.14#

如果为 true,则调用需要选择器解析为单个元素。如果给定的选择器解析为多个元素,则调用会引发异常。

When true, the call requires selector to resolve to a single element. If given selector resolves to more than one element, the call throws an exception.

最长时间(以毫秒为单位)。默认为 0 - 没有超时。可以通过配置中的 actionTimeout 选项或使用 browserContext.setDefaultTimeout()page.setDefaultTimeout() 方法更改默认值。

Maximum time in milliseconds. Defaults to 0 - no timeout. The default value can be changed via actionTimeout option in the config, or by using the browserContext.setDefaultTimeout() or page.setDefaultTimeout() methods.

  • trial boolean (optional) Added in: v1.11#

设置后,此方法仅执行 actionability 检查并跳过该操作。默认为 false。等待元素准备好执行操作而不执行该操作很有用。

When set, this method only performs the actionability checks and skips the action. Defaults to false. Useful to wait until the element is ready for the action without performing it.


textContent

Added in: v1.8 page.textContent
劝阻

请改用基于定位器的 locator.textContent()。了解有关 locators 的更多信息。

Use locator-based locator.textContent() instead. Read more about locators.

返回 element.textContent

Returns element.textContent.

用法

Usage

await page.textContent(selector);
await page.textContent(selector, options);

参数

Arguments

用于搜索元素的选择器。如果有多个元素满足选择器,则将使用第一个元素。

A selector to search for an element. If there are multiple elements satisfying the selector, the first will be used.

  • options Object (optional)

    • strict boolean (optional) Added in: v1.14#

如果为 true,则调用需要选择器解析为单个元素。如果给定的选择器解析为多个元素,则调用会引发异常。

When true, the call requires selector to resolve to a single element. If given selector resolves to more than one element, the call throws an exception.

最长时间(以毫秒为单位)。默认为 0 - 没有超时。可以通过配置中的 actionTimeout 选项或使用 browserContext.setDefaultTimeout()page.setDefaultTimeout() 方法更改默认值。

Maximum time in milliseconds. Defaults to 0 - no timeout. The default value can be changed via actionTimeout option in the config, or by using the browserContext.setDefaultTimeout() or page.setDefaultTimeout() methods.

返回

Returns


type

Added in: v1.8 page.type
已弃用

在大多数情况下,你应该使用 locator.fill()。如果页面上有特殊的键盘处理,则只需一一按键即可 - 在本例中使用 locator.pressSequentially()

In most cases, you should use locator.fill() instead. You only need to press keys one by one if there is special keyboard handling on the page - in this case use locator.pressSequentially().

为文本中的每个字符发送 keydownkeypress/inputkeyup 事件。page.type 可用于发送细粒度的键盘事件。要在表单字段中填写值,请使用 page.fill()

Sends a keydown, keypress/input, and keyup event for each character in the text. page.type can be used to send fine-grained keyboard events. To fill values in form fields, use page.fill().

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

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

用法

Usage

参数

Arguments

用于搜索元素的选择器。如果有多个元素满足选择器,则将使用第一个元素。

A selector to search for an element. If there are multiple elements satisfying the selector, the first will be used.

要输入到焦点元素中的文本。

A text to type into a focused element.

按键之间的等待时间(以毫秒为单位)。默认为 0。

Time to wait between key presses in milliseconds. Defaults to 0.

启动导航的操作正在等待这些导航发生并开始加载页面。你可以通过设置此标志来选择不等待。仅在特殊情况下才需要此选项,例如导航到无法访问的页面。默认为 false

Actions that initiate navigations are waiting for these navigations to happen and for pages to start loading. You can opt out of waiting via setting this flag. You would only need this option in the exceptional cases such as navigating to inaccessible pages. Defaults to false.

  • strict boolean (optional) Added in: v1.14#

如果为 true,则调用需要选择器解析为单个元素。如果给定的选择器解析为多个元素,则调用会引发异常。

When true, the call requires selector to resolve to a single element. If given selector resolves to more than one element, the call throws an exception.

最长时间(以毫秒为单位)。默认为 0 - 没有超时。可以通过配置中的 actionTimeout 选项或使用 browserContext.setDefaultTimeout()page.setDefaultTimeout() 方法更改默认值。

Maximum time in milliseconds. Defaults to 0 - no timeout. The default value can be changed via actionTimeout option in the config, or by using the browserContext.setDefaultTimeout() or page.setDefaultTimeout() methods.


uncheck

Added in: v1.8 page.uncheck
劝阻

请改用基于定位器的 locator.uncheck()。了解有关 locators 的更多信息。

Use locator-based locator.uncheck() instead. Read more about locators.

该方法通过执行以下步骤取消选中与 selector 匹配的元素:

This method unchecks an element matching selector by performing the following steps:

  1. 查找与 selector 匹配的元素。如果没有,请等待,直到将匹配的元素附加到 DOM。

    Find an element matching selector. If there is none, wait until a matching element is attached to the DOM.

  2. 确保匹配的元素是复选框或单选输入。如果不是,该方法将抛出异常。如果该元素已取消选中,则此方法立即返回。

    Ensure that matched element is a checkbox or a radio input. If not, this method throws. If the element is already unchecked, this method returns immediately.

  3. 等待 actionability 检查匹配的元素,除非设置了 force 选项。如果在检查期间该元素被分离,则会重试整个操作。

    Wait for actionability checks on the matched element, unless force option is set. If the element is detached during the checks, the whole action is retried.

  4. 如果需要,将元素滚动到视图中。

    Scroll the element into view if needed.

  5. 使用 page.mouse 单击元素的中心。

    Use page.mouse to click in the center of the element.

  6. 等待启动的导航成功或失败,除非设置了 noWaitAfter 选项。

    Wait for initiated navigations to either succeed or fail, unless noWaitAfter option is set.

  7. 确保该元素现在未被选中。如果不是,该方法将抛出异常。

    Ensure that the element is now unchecked. If not, this method throws.

当所有组合步骤在指定的 timeout 时间内尚未完成时,此方法将抛出 TimeoutError。传递零超时会禁用此功能。

When all steps combined have not finished during the specified timeout, this method throws a TimeoutError. Passing zero timeout disables this.

用法

Usage

await page.uncheck(selector);
await page.uncheck(selector, options);

参数

Arguments

用于搜索元素的选择器。如果有多个元素满足选择器,则将使用第一个元素。

A selector to search for an element. If there are multiple elements satisfying the selector, the first will be used.

是否绕过 actionability 检查。默认为 false

Whether to bypass the actionability checks. Defaults to false.

启动导航的操作正在等待这些导航发生并开始加载页面。你可以通过设置此标志来选择不等待。仅在特殊情况下才需要此选项,例如导航到无法访问的页面。默认为 false

Actions that initiate navigations are waiting for these navigations to happen and for pages to start loading. You can opt out of waiting via setting this flag. You would only need this option in the exceptional cases such as navigating to inaccessible pages. Defaults to false.

相对于元素填充框左上角使用的点。如果未指定,则使用元素的一些可见点。

A point to use relative to the top-left corner of element padding box. If not specified, uses some visible point of the element.

  • strict boolean (optional) Added in: v1.14#

如果为 true,则调用需要选择器解析为单个元素。如果给定的选择器解析为多个元素,则调用会引发异常。

When true, the call requires selector to resolve to a single element. If given selector resolves to more than one element, the call throws an exception.

最长时间(以毫秒为单位)。默认为 0 - 没有超时。可以通过配置中的 actionTimeout 选项或使用 browserContext.setDefaultTimeout()page.setDefaultTimeout() 方法更改默认值。

Maximum time in milliseconds. Defaults to 0 - no timeout. The default value can be changed via actionTimeout option in the config, or by using the browserContext.setDefaultTimeout() or page.setDefaultTimeout() methods.

  • trial boolean (optional) Added in: v1.11#

设置后,此方法仅执行 actionability 检查并跳过该操作。默认为 false。等待元素准备好执行操作而不执行该操作很有用。

When set, this method only performs the actionability checks and skips the action. Defaults to false. Useful to wait until the element is ready for the action without performing it.


waitForNavigation

Added in: v1.8 page.waitForNavigation
已弃用

这种方法本质上是有问题的,请使用 page.waitForURL() 代替。

This method is inherently racy, please use page.waitForURL() instead.

等待主框架导航并返回主资源响应。如果存在多个重定向,导航将使用最后一个重定向的响应进行解析。如果导航到不同的锚点或由于历史 API 使用而导航,则导航将解析为 null

Waits for the main frame navigation and returns the main resource response. In case of multiple redirects, the navigation will resolve with the response of the last redirect. In case of navigation to a different anchor or navigation due to History API usage, the navigation will resolve with null.

用法

Usage

当页面导航到新 URL 或重新加载时,此问题就会解决。当你运行将间接导致页面导航的代码时,它非常有用。例如 单击目标有一个 onclick 处理程序,可触发 setTimeout 的导航。考虑这个例子:

This resolves when the page navigates to a new URL or reloads. It is useful for when you run code which will indirectly cause the page to navigate. e.g. The click target has an onclick handler that triggers navigation from a setTimeout. Consider this example:

// Start waiting for navigation before clicking. Note no await.
const navigationPromise = page.waitForNavigation();
await page.getByText('Navigate after timeout').click();
await navigationPromise;
注意

使用 历史 API 更改 URL 被视为导航。

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

参数

Arguments

最大操作时间(以毫秒为单位)。默认为 0 - 没有超时。可以通过配置中的 navigationTimeout 选项或使用 browserContext.setDefaultNavigationTimeout()browserContext.setDefaultTimeout()page.setDefaultNavigationTimeout()page.setDefaultTimeout() 方法更改默认值。

Maximum operation time in milliseconds. Defaults to 0 - no timeout. The default value can be changed via navigationTimeout option in the config, or by using the browserContext.setDefaultNavigationTimeout(), browserContext.setDefaultTimeout(), page.setDefaultNavigationTimeout() or page.setDefaultTimeout() methods.

在等待导航时接收 URL 进行匹配的通配符模式、正则表达式模式或谓词。请注意,如果参数是不带通配符的字符串,则该方法将等待导航到与该字符串完全相同的 URL。

A glob pattern, regex pattern or predicate receiving URL to match while waiting for the navigation. Note that if the parameter is a string without wildcard characters, the method will wait for navigation to URL that is exactly equal to the string.

  • waitUntil "load"|"domcontentloaded"|"networkidle"|"commit"(可选)#

    waitUntil "load"|"domcontentloaded"|"networkidle"|"commit" (optional)#

    什么时候才认为操作成功,默认为 load。事件可以是:

    When to consider operation succeeded, defaults to load. Events can be either:

    • 'domcontentloaded' - 认为操作在 DOMContentLoaded 事件触发时完成。

      'domcontentloaded' - consider operation to be finished when the DOMContentLoaded event is fired.

    • 'load' - 认为操作在 load 事件触发时完成。

      'load' - consider operation to be finished when the load event is fired.

    • 'networkidle' - 不鼓励在至少 500 毫秒内没有网络连接时考虑操作完成。不要使用此方法进行测试,而是依靠网络断言来评估准备情况。

      'networkidle' - DISCOURAGED consider operation to be finished when there are no network connections for at least 500 ms. Don't use this method for testing, rely on web assertions to assess readiness instead.

    • 'commit' - 当收到网络响应并且文档开始加载时,认为操作完成。

      'commit' - consider operation to be finished when network response is received and the document started loading.

返回

Returns


waitForSelector

Added in: v1.8 page.waitForSelector
劝阻

请改用断言可见性的 Web 断言或基于定位器的 locator.waitFor()。了解有关 locators 的更多信息。

Use web assertions that assert visibility or a locator-based locator.waitFor() instead. Read more about locators.

当选择器指定的元素满足 state 选项时返回。如果等待 hiddendetached,则返回 null

Returns when element specified by selector satisfies state option. Returns null if waiting for hidden or detached.

注意

Playwright 在执行操作之前自动等待元素准备好。使用 定位器 对象和 Web 优先断言使代码无需等待选择器。

Playwright automatically waits for element to be ready before performing an action. Using Locator objects and web-first assertions makes the code wait-for-selector-free.

等待 selector 满足 state 选项(从 dom 中出现/消失,或者变得可见/隐藏)。如果在调用方法 selector 时已经满足条件,则该方法将立即返回。如果选择器在 timeout 毫秒内不满足条件,该函数将抛出异常。

Wait for the selector to satisfy state option (either appear/disappear from dom, or become visible/hidden). If at the moment of calling the method selector already satisfies the condition, the method will return immediately. If the selector doesn't satisfy the condition for the timeout milliseconds, the function will throw.

用法

Usage

此方法适用于多种导航:

This method works across navigations:

const { chromium } = require('playwright');  // Or 'firefox' or 'webkit'.

(async () => {
const browser = await chromium.launch();
const page = await browser.newPage();
for (const currentURL of ['https://google.com', 'https://bbc.com']) {
await page.goto(currentURL);
const element = await page.waitForSelector('img');
console.log('Loaded image: ' + await element.getAttribute('src'));
}
await browser.close();
})();

参数

Arguments

要查询的选择器。

A selector to query for.

  • state "attached"|"detached"|"visible"|"hidden"(可选)#

    state "attached"|"detached"|"visible"|"hidden" (optional)#

    默认为 'visible'。可以是:

    Defaults to 'visible'. Can be either:

    • 'attached' - 等待元素出现在 DOM 中。

      'attached' - wait for element to be present in DOM.

    • 'detached' - 等待 DOM 中不存在元素。

      'detached' - wait for element to not be present in DOM.

    • 'visible' - 等待元素具有非空边界框并且没有 visibility:hidden。请注意,没有任何内容或具有 display:none 的元素具有空边界框,并且不被视为可见。

      'visible' - wait for element to have non-empty bounding box and no visibility:hidden. Note that element without any content or with display:none has an empty bounding box and is not considered visible.

    • 'hidden' - 等待元素从 DOM 分离,或者有一个空的边界框或 visibility:hidden。这与 'visible' 选项相反。

      'hidden' - wait for element to be either detached from DOM, or have an empty bounding box or visibility:hidden. This is opposite to the 'visible' option.

    • strict boolean (optional) Added in: v1.14#

如果为 true,则调用需要选择器解析为单个元素。如果给定的选择器解析为多个元素,则调用会引发异常。

When true, the call requires selector to resolve to a single element. If given selector resolves to more than one element, the call throws an exception.

最长时间(以毫秒为单位)。默认为 0 - 没有超时。可以通过配置中的 actionTimeout 选项或使用 browserContext.setDefaultTimeout()page.setDefaultTimeout() 方法更改默认值。

Maximum time in milliseconds. Defaults to 0 - no timeout. The default value can be changed via actionTimeout option in the config, or by using the browserContext.setDefaultTimeout() or page.setDefaultTimeout() methods.

返回

Returns


waitForTimeout

Added in: v1.8 page.waitForTimeout
劝阻

永远不要在生产中等待超时。等待时间的测试本质上是不稳定的。使用自动等待的 定位器 操作和 Web 断言。

Never wait for timeout in production. Tests that wait for time are inherently flaky. Use Locator actions and web assertions that wait automatically.

等待给定的 timeout(以毫秒为单位)。

Waits for the given timeout in milliseconds.

请注意,page.waitForTimeout() 只能用于调试。在生产中使用计时器进行的测试将会很不稳定。使用网络事件、选择器变得可见等信号来代替。

Note that page.waitForTimeout() should only be used for debugging. Tests using the timer in production are going to be flaky. Use signals such as network events, selectors becoming visible and others instead.

用法

Usage

// wait for 1 second
await page.waitForTimeout(1000);

参数

Arguments

等待超时

A timeout to wait for