Skip to main content

框架

在每个时间点,页面都会通过 page.mainFrame()frame.childFrames() 方法公开其当前的框架树。

At every point of time, page exposes its current frame tree via the page.mainFrame() and frame.childFrames() methods.

框架 对象的生命周期由三个事件控制,在页面对象上调度:

Frame object's lifecycle is controlled by three events, dispatched on the page object:

转储框架树的示例:

An example of dumping frame tree:

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

(async () => {
const browser = await firefox.launch();
const page = await browser.newPage();
await page.goto('https://www.google.com/chrome/browser/canary.html');
dumpFrameTree(page.mainFrame(), '');
await browser.close();

function dumpFrameTree(frame, indent) {
console.log(indent + frame.url());
for (const child of frame.childFrames())
dumpFrameTree(child, indent + ' ');
}
})();

方法

Methods

addScriptTag

Added in: v1.8 frame.addScriptTag

当脚本的 onload 触发或脚本内容注入框架时返回添加的标签。

Returns the added tag when the script's onload fires or when the script content was injected into frame.

<script> 标记添加到具有所需 url 或内容的页面中。

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

用法

Usage

await frame.addScriptTag();
await frame.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 frame.addStyleTag

当样式表的 onload 触发或 CSS 内容注入框架时返回添加的标签。

Returns the added tag when the stylesheet's onload fires or when the CSS content was injected into frame.

<link rel="stylesheet"> 标记添加到具有所需 url 的页面中,或将 <style type="text/css"> 标记添加到内容中。

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

用法

Usage

await frame.addStyleTag();
await frame.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


childFrames

Added in: v1.8 frame.childFrames

用法

Usage

frame.childFrames();

返回

Returns


content

Added in: v1.8 frame.content

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

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

用法

Usage

await frame.content();

返回

Returns


dragAndDrop

Added in: v1.13 frame.dragAndDrop

用法

Usage

await frame.dragAndDrop(source, target);
await frame.dragAndDrop(source, target, options);

参数

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.


evaluate

Added in: v1.8 frame.evaluate

返回 pageFunction 的返回值。

Returns the return value of pageFunction.

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

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

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

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

用法

Usage

const result = await frame.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 frame.evaluate('1 + 2')); // prints "3"

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

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

const bodyHandle = await frame.evaluate('document.body');
const html = await frame.evaluate(([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 frame.evaluateHandle

pageFunction 的返回值作为 JSHandle 返回。

Returns the return value of pageFunction as a JSHandle.

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

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

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

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

用法

Usage

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

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

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

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

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

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

const aHandle = await frame.evaluateHandle(() => document.body);
const resultHandle = await frame.evaluateHandle(([body, suffix]) =>
body.innerHTML + suffix, [aHandle, 'hello'],
);
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


frameElement

Added in: v1.8 frame.frameElement

返回对应于该帧的 frameiframe 元素句柄。

Returns the frame or iframe element handle which corresponds to this frame.

这是 elementHandle.contentFrame() 的逆。请注意,返回的句柄实际上属于父框架。

This is an inverse of elementHandle.contentFrame(). Note that returned handle actually belongs to the parent frame.

如果在 frameElement() 返回之前框架已分离,则此方法会引发错误。

This method throws an error if the frame has been detached before frameElement() returns.

用法

Usage

const frameElement = await frame.frameElement();
const contentFrame = await frameElement.contentFrame();
console.log(frame === contentFrame); // -> true

返回

Returns


frameLocator

Added in: v1.17 frame.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 = frame.frameLocator('#my-iframe').getByText('Submit');
await locator.click();

参数

Arguments

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

A selector to use when resolving DOM element.

返回

Returns


getByAltText

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


goto

Added in: v1.8frame.goto

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

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

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

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 frame.goto(url);
await frame.goto(url, options);

参数

Arguments

将框架导航到的 URL。url 应包含方案,例如 https://

URL to navigate frame to. The url should include scheme, e.g. https://.

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


isDetached

Added in: v1.8 frame.isDetached

如果框架已分离,则返回 true,否则返回 false

Returns true if the frame has been detached, or false otherwise.

用法

Usage

frame.isDetached();

返回

Returns


isEnabled

Added in: v1.8 frame.isEnabled

返回元素是否为 enabled

Returns whether the element is enabled.

用法

Usage

await frame.isEnabled(selector);
await frame.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


locator

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

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

Learn more about locators.

用法

Usage

frame.locator(selector);
frame.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


name

Added in: v1.8 frame.name

返回标签中指定的框架的名称属性。

Returns frame's name attribute as specified in the tag.

如果名称为空,则返回 id 属性。

If the name is empty, returns the id attribute instead.

注意

该值在框架创建时计算一次,如果以后属性更改,该值将不会更新。

This value is calculated once when the frame is created, and will not update if the attribute is changed later.

用法

Usage

frame.name();

返回

Returns


page

Added in: v1.8 frame.page

返回包含此框架的页面。

Returns the page containing this frame.

用法

Usage

frame.page();

返回

Returns


parentFrame

Added in: v1.8 frame.parentFrame

父框架(如果有)。分离框架和主框架返回 null

Parent frame, if any. Detached frames and main frames return null.

用法

Usage

frame.parentFrame();

返回

Returns


setContent

Added in: v1.8 frame.setContent

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

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

用法

Usage

await frame.setContent(html);
await frame.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.


title

Added in: v1.8 frame.title

返回页面标题。

Returns the page title.

用法

Usage

await frame.title();

返回

Returns


url

Added in: v1.8 frame.url

返回框架的 url。

Returns frame's url.

用法

Usage

frame.url();

返回

Returns


waitForFunction

Added in: v1.8 frame.waitForFunction

返回 当 pageFunction 返回真值时,返回该值。

Returns when the pageFunction returns a truthy value, returns that value.

用法

Usage

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

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

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

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

要将参数传递给 frame.waitForFunction 函数的谓词:

To pass an argument to the predicate of frame.waitForFunction function:

const selector = '.foo';
await frame.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 frame.waitForLoadState

等待达到所需的加载状态。

Waits for the required load state to be reached.

当框架达到所需的加载状态(默认情况下为 load)时,该函数将返回。调用此方法时必须已提交导航。如果当前文档已达到所需状态,则立即解决。

This returns when the frame 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 frame.click('button'); // Click triggers navigation.
await frame.waitForLoadState(); // Waits for 'load' state by default.

参数

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.


waitForURL

Added in: v1.11 frame.waitForURL

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

Waits for the frame to navigate to the given URL.

用法

Usage

await frame.click('a.delayed-navigation'); // Clicking the link will indirectly cause a navigation
await frame.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.


已弃用

Deprecated

$ {#}

Added in: v1.9 frame.$
劝阻

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

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

返回指向框架元素的 ElementHandle。

Returns the ElementHandle pointing to the frame element.

提醒

不鼓励使用 ElementHandle,而是使用 定位器 对象和 Web 优先断言。

The use of ElementHandle is discouraged, use Locator objects and web-first assertions instead.

该方法在框架内查找与指定选择器匹配的元素。如果没有元素与选择器匹配,则返回 null

The method finds an element matching the specified selector within the frame. If no elements match the selector, returns null.

用法

Usage

await frame.$(selector);
await frame.$(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 frame.$$
劝阻

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

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

返回指向框架元素的 ElementHandles。

Returns the ElementHandles pointing to the frame elements.

提醒

不鼓励使用 ElementHandle,而是使用 定位器 对象。

The use of ElementHandle is discouraged, use Locator objects instead.

该方法查找框架内与指定选择器匹配的所有元素。如果没有元素与选择器匹配,则返回空数组。

The method finds all elements matching the specified selector within the frame. If no elements match the selector, returns empty array.

用法

Usage

await frame.$$(selector);

参数

Arguments

要查询的选择器。

A selector to query for.

返回

Returns


$eval

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

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

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

返回 pageFunction 的返回值。

Returns the return value of pageFunction.

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

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

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

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

用法

Usage

const searchValue = await frame.$eval('#search', el => el.value);
const preloadHref = await frame.$eval('link[rel=preload]', el => el.href);
const html = await frame.$eval('.main-container', (e, suffix) => e.outerHTML + suffix, 'hello');

参数

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 frame.$$eval
劝阻

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

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

返回 pageFunction 的返回值。

Returns the return value of pageFunction.

该方法查找框架内与指定选择器匹配的所有元素,并将匹配元素的数组作为第一个参数传递给 pageFunction

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

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

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

用法

Usage

const divsCounts = await frame.$$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


check

Added in: v1.8 frame.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 frame.check(selector);
await frame.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 frame.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 frame.click(selector);
await frame.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 frame.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.

注意

frame.dblclick() 调度两个 click 事件和一个 dblclick 事件。

frame.dblclick() dispatches two click events and a single dblclick event.

用法

Usage

await frame.dblclick(selector);
await frame.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 frame.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 frame.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 frame.evaluateHandle(() => new DataTransfer());
await frame.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 frame.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 frame.fill(selector, value);
await frame.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 frame.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 frame.focus(selector);
await frame.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 frame.getAttribute
劝阻

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

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

返回元素属性值。

Returns element attribute value.

用法

Usage

await frame.getAttribute(selector, name);
await frame.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 frame.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 frame.hover(selector);
await frame.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 frame.innerHTML
劝阻

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

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

返回 element.innerHTML

Returns element.innerHTML.

用法

Usage

await frame.innerHTML(selector);
await frame.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 frame.innerText
劝阻

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

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

返回 element.innerText

Returns element.innerText.

用法

Usage

await frame.innerText(selector);
await frame.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 frame.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 frame.inputValue(selector);
await frame.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 frame.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 frame.isChecked(selector);
await frame.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 frame.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 frame.isDisabled(selector);
await frame.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 frame.isEditable
劝阻

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

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

返回元素是否为 editable

Returns whether the element is editable.

用法

Usage

await frame.isEditable(selector);
await frame.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


isHidden

Added in: v1.8 frame.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 frame.isHidden(selector);
await frame.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. frame.isHidden() does not wait for the element to become hidden and returns immediately.

返回

Returns


isVisible

Added in: v1.8 frame.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 frame.isVisible(selector);
await frame.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. frame.isVisible() does not wait for the element to become visible and returns immediately.

返回

Returns


press

Added in: v1.8 frame.press
劝阻

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

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

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

await frame.press(selector, key);
await frame.press(selector, key, options);

参数

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 frame.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
frame.selectOption('select#colors', 'blue');

// single selection matching both the value and the label
frame.selectOption('select#colors', { label: 'Blue' });

// multiple selection
frame.selectOption('select#colors', 'red', 'green', 'blue');

参数

Arguments

要查询的选择器。

A selector to query for.

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 frame.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 frame.setChecked(selector, checked);
await frame.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 frame.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 frame.setInputFiles(selector, files);
await frame.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 frame.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.

注意

frame.tap() 要求浏览器上下文的 hasTouch 选项设置为 true。

frame.tap() requires that the hasTouch option of the browser context be set to true.

用法

Usage

await frame.tap(selector);
await frame.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 frame.textContent
劝阻

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

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

返回 element.textContent

Returns element.textContent.

用法

Usage

await frame.textContent(selector);
await frame.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 frame.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 事件。frame.type 可用于发送细粒度的键盘事件。要在表单字段中填写值,请使用 frame.fill()

Sends a keydown, keypress/input, and keyup event for each character in the text. frame.type can be used to send fine-grained keyboard events. To fill values in form fields, use frame.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 frame.uncheck
劝阻

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

Use locator-based locator.uncheck() 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 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 frame.uncheck(selector);
await frame.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 frame.waitForNavigation
已弃用

这种方法本质上是有问题的,请使用 frame.waitForURL() 代替。

This method is inherently racy, please use frame.waitForURL() instead.

等待框架导航并返回主要资源响应。如果存在多个重定向,导航将使用最后一个重定向的响应进行解析。如果导航到不同的锚点或由于历史 API 使用而导航,则导航将解析为 null

Waits for the 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。当你运行将间接导致框架导航的代码时,它非常有用。考虑这个例子:

This method waits for the frame to navigate to a new URL. It is useful for when you run code which will indirectly cause the frame to navigate. 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 frame.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 make 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.mainFrame().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 frame.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.

请注意,frame.waitForTimeout() 只能用于调试。在生产中使用计时器进行的测试将会很不稳定。使用网络事件、选择器变得可见等信号来代替。

Note that frame.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

await frame.waitForTimeout(timeout);

参数

Arguments

等待超时

A timeout to wait for