Skip to main content

定位器

定位器是 Playwright 自动等待和重试能力的核心部分。简而言之,定位器代表了一种随时在页面上查找元素的方法。可以使用 page.locator() 方法创建定位器。

Locators are the central piece of Playwright's auto-waiting and retry-ability. In a nutshell, locators represent a way to find element(s) on the page at any moment. A locator can be created with the page.locator() method.

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

Learn more about locators.


方法

Methods

all

Added in: v1.29 locator.all

当定位器指向元素列表时,这将返回一个定位器数组,指向它们各自的元素。

When the locator points to a list of elements, this returns an array of locators, pointing to their respective elements.

注意

locator.all() 不会等待元素与定位器匹配,而是立即返回页面中存在的任何内容。当元素列表动态变化时,locator.all() 将产生不可预测且不稳定的结果。当元素列表稳定但动态加载时,请在调用 locator.all() 之前等待完整列表完成加载。

locator.all() does not wait for elements to match the locator, and instead immediately returns whatever is present in the page. When the list of elements changes dynamically, locator.all() will produce unpredictable and flaky results. When the list of elements is stable, but loaded dynamically, wait for the full list to finish loading before calling locator.all().

用法

Usage

for (const li of await page.getByRole('listitem').all())
await li.click();

返回

Returns


allInnerTexts

Added in: v1.14 locator.allInnerTexts

返回所有匹配节点的 node.innerText 值数组。

Returns an array of node.innerText values for all matching nodes.

断言文本

如果你需要在页面上断言文本,请首选 expect(locator).toHaveText()useInnerText 选项以避免不稳定。详细信息请参见 断言指南

If you need to assert text on the page, prefer expect(locator).toHaveText() with useInnerText option to avoid flakiness. See assertions guide for more details.

用法

Usage

const texts = await page.getByRole('link').allInnerTexts();

返回

Returns


allTextContents

Added in: v1.14 locator.allTextContents

返回所有匹配节点的 node.textContent 值数组。

Returns an array of node.textContent values for all matching nodes.

断言文本

如果你需要在页面上断言文本,请首选 expect(locator).toHaveText() 以避免不稳定。详细信息请参见 断言指南

If you need to assert text on the page, prefer expect(locator).toHaveText() to avoid flakiness. See assertions guide for more details.

用法

Usage

const texts = await page.getByRole('link').allTextContents();

返回

Returns


and

Added in: v1.34 locator.and

创建一个与此定位器和参数定位器相匹配的定位器。

Creates a locator that matches both this locator and the argument locator.

用法

Usage

以下示例查找具有特定标题的按钮。

The following example finds a button with a specific title.

const button = page.getByRole('button').and(page.getByTitle('Subscribe'));

参数

Arguments

要匹配的附加定位器。

Additional locator to match.

返回

Returns


blur

Added in: v1.28 locator.blur

对元素调用 blur

Calls blur on the element.

用法

Usage

await locator.blur();
await locator.blur(options);

参数

Arguments

最长时间(以毫秒为单位)。默认为 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.


boundingBox

Added in: v1.14 locator.boundingBox

此方法返回与定位器匹配的元素的边界框,如果元素不可见,则返回 null。边界框是相对于主框架视口计算的 - 这通常与浏览器窗口相同。

This method returns the bounding box of the element matching the locator, or null if the element is not visible. The bounding box is calculated relative to the main frame viewport - which is usually the same as the browser window.

用法

Usage

const box = await page.getByRole('button').boundingBox();
await page.mouse.click(box.x + box.width / 2, box.y + box.height / 2);

参数

Arguments

最长时间(以毫秒为单位)。默认为 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

元素的 x 坐标(以像素为单位)。

the x coordinate of the element in pixels.

元素的 y 坐标(以像素为单位)。

the y coordinate of the element in pixels.

元素的宽度(以像素为单位)。

the width of the element in pixels.

元素的高度(以像素为单位)。

the height of the element in pixels.

细节

Details

滚动会影响返回的边界框,与 Element.getBoundingClientRect 类似。这意味着 x 和/或 y 可能为负。

Scrolling affects the returned bounding box, similarly to Element.getBoundingClientRect. That means x and/or y may be negative.

Element.getBoundingClientRect 不同,子框架中的元素返回相对于主框架的边界框。

Elements from child frames return the bounding box relative to the main frame, unlike the Element.getBoundingClientRect.

假设页面是静态的,则使用边界框坐标来执行输入是安全的。例如,以下代码片段应单击元素的中心。

Assuming the page is static, it is safe to use bounding box coordinates to perform input. For example, the following snippet should click the center of the element.


check

Added in: v1.14 locator.check

确保复选框或单选元素已选中。

Ensure that checkbox or radio element is checked.

用法

Usage

await page.getByRole('checkbox').check();

参数

Arguments

是否绕过 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.

最长时间(以毫秒为单位)。默认为 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.

细节

Details

执行以下步骤:

Performs the following steps:

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

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

  2. 等待 actionability 检查元素,除非设置了 force 选项。

    Wait for actionability checks on the element, unless force option is set.

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

    Scroll the element into view if needed.

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

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

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

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

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

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

如果该元素在操作过程中的任何时刻与 DOM 分离,则此方法会抛出异常。

If the element is detached from the DOM at any moment during the action, 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.


clear

Added in: v1.28 locator.clear

清除输入字段。

Clear the input field.

用法

Usage

await page.getByRole('textbox').clear();

参数

Arguments

是否绕过 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.

最长时间(以毫秒为单位)。默认为 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.

细节

Details

该方法等待 actionability 检查,聚焦元素,清除它并在清除后触发 input 事件。

This method waits for actionability checks, focuses the element, clears it and triggers an input event after clearing.

如果目标元素不是 <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 cleared instead.


click

Added in: v1.14 locator.click

单击一个元素。

Click an element.

用法

Usage

单击一个按钮:

Click a button:

await page.getByRole('button').click();

按住 Shift 键并右键单击画布上的特定位置:

Shift-right-click at a specific position on a canvas:

await page.locator('canvas').click({
button: 'right',
modifiers: ['Shift'],
position: { x: 23, y: 32 },
});

参数

Arguments

  • 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.

最长时间(以毫秒为单位)。默认为 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.

细节

Details

此方法通过执行以下步骤来单击元素:

This method clicks the element by performing the following steps:

  1. 等待 actionability 检查元素,除非设置了 force 选项。

    Wait for actionability checks on the element, unless force option is set.

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

    Scroll the element into view if needed.

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

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

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

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

如果该元素在操作过程中的任何时刻与 DOM 分离,则此方法会抛出异常。

If the element is detached from the DOM at any moment during the action, 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.


count

Added in: v1.14 locator.count

返回与定位器匹配的元素数。

Returns the number of elements matching the locator.

断言计数

如果你需要断言页面上的元素数量,请首选 expect(locator).toHaveCount() 以避免不稳定。详细信息请参见 断言指南

If you need to assert the number of elements on the page, prefer expect(locator).toHaveCount() to avoid flakiness. See assertions guide for more details.

用法

Usage

const count = await page.getByRole('listitem').count();

返回

Returns


dblclick

Added in: v1.14 locator.dblclick

双击一个元素。

Double-click an element.

用法

Usage

await locator.dblclick();
await locator.dblclick(options);

参数

Arguments

  • 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.

最长时间(以毫秒为单位)。默认为 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.

细节

Details

此方法通过执行以下步骤双击该元素:

This method double clicks the element by performing the following steps:

  1. 等待 actionability 检查元素,除非设置了 force 选项。

    Wait for actionability checks on the element, unless force option is set.

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

    Scroll the element into view if needed.

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

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

  4. 等待启动的导航成功或失败,除非设置了 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.

如果该元素在操作过程中的任何时刻与 DOM 分离,则此方法会抛出异常。

If the element is detached from the DOM at any moment during the action, 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.

注意

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

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


dispatchEvent

Added in: v1.14 locator.dispatchEvent

以编程方式在匹配元素上调度事件。

Programmatically dispatch an event on the matching element.

用法

Usage

await locator.dispatchEvent('click');

参数

Arguments

DOM 事件类型:"click""dragstart"

DOM event type: "click", "dragstart", etc.

可选的特定于事件的初始化属性。

Optional event-specific initialization properties.

最长时间(以毫秒为单位)。默认为 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.

细节

Details

上面的代码片段在元素上调度 click 事件。无论元素的可见性状态如何,都会调度 click。这相当于调用 element.click()

The snippet above 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().

在底层,它根据给定的 type 创建事件的实例,使用 eventInit 属性对其进行初始化,并将其分派到元素上。事件默认为 composedcancelable 和 bubble。

Under the hood, it creates an instance of an event based on the given type, initializes it with eventInit properties and dispatches it on the element. Events are composed, cancelable and bubble by default.

由于 eventInit 是特定于事件的,因此请参阅事件文档以获取初始属性列表:

Since eventInit is event-specific, please refer to the events documentation for the lists of initial properties:

如果你希望将活动对象传递到事件中,你还可以指定 JSHandle 作为属性值:

You can also specify JSHandle as the property value if you want live objects to be passed into the event:

// Note you can only create DataTransfer in Chromium and Firefox
const dataTransfer = await page.evaluateHandle(() => new DataTransfer());
await locator.dispatchEvent('dragstart', { dataTransfer });

dragTo

Added in: v1.18 locator.dragTo

将源元素拖向目标元素并将其放下。

Drag the source element towards the target element and drop it.

用法

Usage

const source = page.locator('#source');
const target = page.locator('#target');

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

参数

Arguments

要拖动到的元素的定位器。

Locator of the element to drag to.

是否绕过 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.

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

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.

细节

Details

此方法将定位器拖动到另一个目标定位器或目标位置。它将首先移动到源元素,执行 mousedown,然后移动到目标元素或位置并执行 mouseup

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


evaluate

Added in: v1.14 locator.evaluate

在页面中执行 JavaScript 代码,将匹配元素作为参数。

Execute JavaScript code in the page, taking the matching element as an argument.

用法

Usage

const tweets = page.locator('.tweet .retweets');
expect(await tweets.evaluate(node => node.innerText)).toBe('10 retweets');

参数

Arguments

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

Function to be evaluated in the page context.

传递给 pageFunction 的可选参数。

Optional argument to pass to pageFunction.

最长时间(以毫秒为单位)。默认为 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

细节

Details

返回 pageFunction 的返回值,调用时将匹配元素作为第一个参数,将 arg 作为第二个参数。

Returns the return value of pageFunction, called with the matching element as a first argument, and arg as a second argument.

如果 pageFunction 返回 Promise,此方法将等待 Promise 解析并返回其值。

If pageFunction returns a Promise, this method will wait for the promise to resolve and return its value.

如果 pageFunction 抛出或拒绝,则此方法抛出。

If pageFunction throws or rejects, this method throws.


evaluateAll

Added in: v1.14 locator.evaluateAll

在页面中执行 JavaScript 代码,将所有匹配元素作为参数。

Execute JavaScript code in the page, taking all matching elements as an argument.

用法

Usage

const locator = page.locator('div');
const moreThanTen = await locator.evaluateAll((divs, min) => divs.length > min, 10);

参数

Arguments

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

Function to be evaluated in the page context.

传递给 pageFunction 的可选参数。

Optional argument to pass to pageFunction.

返回

Returns

细节

Details

返回 pageFunction 的返回值,调用时使用所有匹配元素的数组作为第一个参数,使用 arg 作为第二个参数。

Returns the return value of pageFunction, called with an array of all matching elements as a first argument, and arg as a second argument.

如果 pageFunction 返回 Promise,此方法将等待 Promise 解析并返回其值。

If pageFunction returns a Promise, this method will wait for the promise to resolve and return its value.

如果 pageFunction 抛出或拒绝,则此方法抛出。

If pageFunction throws or rejects, this method throws.


evaluateHandle

Added in: v1.14 locator.evaluateHandle

在页面中执行 JavaScript 代码,将匹配元素作为参数,并返回 JSHandle 和结果。

Execute JavaScript code in the page, taking the matching element as an argument, and return a JSHandle with the result.

用法

Usage

await locator.evaluateHandle(pageFunction);
await locator.evaluateHandle(pageFunction, arg, options);

参数

Arguments

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

Function to be evaluated in the page context.

传递给 pageFunction 的可选参数。

Optional argument to pass to pageFunction.

最长时间(以毫秒为单位)。默认为 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

细节

Details

pageFunction 的返回值返回为 aJSHandle,调用时将匹配元素作为第一个参数,将 arg 作为第二个参数。

Returns the return value of pageFunction as aJSHandle, called with the matching element as a first argument, and arg as a second argument.

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

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

如果 pageFunction 返回 Promise,此方法将等待 Promise 解析并返回其值。

If pageFunction returns a Promise, this method will wait for the promise to resolve and return its value.

如果 pageFunction 抛出或拒绝,则此方法抛出。

If pageFunction throws or rejects, this method throws.

详细信息请参见 page.evaluateHandle()

See page.evaluateHandle() for more details.


fill

Added in: v1.14 locator.fill

为输入字段设置一个值。

Set a value to the input field.

用法

Usage

await page.getByRole('textbox').fill('example value');

参数

Arguments

<input><textarea>[contenteditable] 元素设置的值。

Value to set 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.

最长时间(以毫秒为单位)。默认为 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.

细节

Details

该方法等待 actionability 检查,聚焦元素,填充它并在填充后触发 input 事件。请注意,你可以传递空字符串来清除输入字段。

This method 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().


filter

Added in: v1.22 locator.filter

此方法根据选项缩小现有定位器的范围,例如按文本过滤。它可以串联起来进行多次过滤。

This method narrows existing locator according to the options, for example filters by text. It can be chained to filter multiple times.

用法

Usage

const rowLocator = page.locator('tr');
// ...
await rowLocator
.filter({ hasText: 'text in column 1' })
.filter({ has: page.getByRole('button', { name: 'column 2 button' }) })
.screenshot();

参数

Arguments

将方法的结果范围缩小到包含与此相对定位器匹配的元素的结果。例如,具有 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


first

Added in: v1.14 locator.first

返回第一个匹配元素的定位器。

Returns locator to the first matching element.

用法

Usage

locator.first();

返回

Returns


focus

Added in: v1.14 locator.focus

在匹配元素上调用 focus

Calls focus on the matching element.

用法

Usage

await locator.focus();
await locator.focus(options);

参数

Arguments

最长时间(以毫秒为单位)。默认为 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.


frameLocator

Added in: v1.17 locator.frameLocator

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

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

用法

Usage

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

参数

Arguments

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

A selector to use when resolving DOM element.

返回

Returns


getAttribute

Added in: v1.14 locator.getAttribute

返回匹配元素的属性值。

Returns the matching element's attribute value.

断言属性

如果你需要断言元素的属性,请首选 expect(locator).toHaveAttribute() 以避免不稳定。详细信息请参见 断言指南

If you need to assert an element's attribute, prefer expect(locator).toHaveAttribute() to avoid flakiness. See assertions guide for more details.

用法

Usage

await locator.getAttribute(name);
await locator.getAttribute(name, options);

参数

Arguments

要获取其值的属性名称。

Attribute name to get the value for.

最长时间(以毫秒为单位)。默认为 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


getByAltText

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


highlight

Added in: v1.20locator.highlight

高亮屏幕上相应的元素。对于调试很有用,不要提交使用 locator.highlight() 的代码。

Highlight the corresponding element(s) on the screen. Useful for debugging, don't commit the code that uses locator.highlight().

用法

Usage

await locator.highlight();

hover

Added in: v1.14locator.hover

将鼠标悬停在匹配的元素上。

Hover over the matching element.

用法

Usage

await page.getByRole('link').hover();

参数

Arguments

是否绕过 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.

最长时间(以毫秒为单位)。默认为 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.

细节

Details

此方法通过执行以下步骤将鼠标悬停在元素上:

This method hovers over the element by performing the following steps:

  1. 等待 actionability 检查元素,除非设置了 force 选项。

    Wait for actionability checks on the element, unless force option is set.

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

    Scroll the element into view if needed.

  3. 使用 page.mouse 将鼠标悬停在元素的中心或指定的 position 上。

    Use page.mouse to hover over the center of the element, or the specified position.

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

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

如果该元素在操作过程中的任何时刻与 DOM 分离,则此方法会抛出异常。

If the element is detached from the DOM at any moment during the action, 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.


innerHTML

Added in: v1.14locator.innerHTML

返回 element.innerHTML

Returns the element.innerHTML.

用法

Usage

await locator.innerHTML();
await locator.innerHTML(options);

参数

Arguments

最长时间(以毫秒为单位)。默认为 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.14locator.innerText

返回 element.innerText

Returns the element.innerText.

断言文本

如果你需要在页面上断言文本,请首选 expect(locator).toHaveText()useInnerText 选项以避免不稳定。详细信息请参见 断言指南

If you need to assert text on the page, prefer expect(locator).toHaveText() with useInnerText option to avoid flakiness. See assertions guide for more details.

用法

Usage

await locator.innerText();
await locator.innerText(options);

参数

Arguments

最长时间(以毫秒为单位)。默认为 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.14 locator.inputValue

返回匹配的 <input><textarea><select> 元素的值。

Returns the value for the matching <input> or <textarea> or <select> element.

断言值

如果你需要断言输入值,请首选 expect(locator).toHaveValue() 以避免不稳定。详细信息请参见 断言指南

If you need to assert input value, prefer expect(locator).toHaveValue() to avoid flakiness. See assertions guide for more details.

用法

Usage

const value = await page.getByRole('textbox').inputValue();

参数

Arguments

最长时间(以毫秒为单位)。默认为 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

细节

Details

抛出不是输入、文本区域或选择的元素。但是,如果该元素位于具有关联的 control<label> 元素内部,则返回控件的值。

Throws elements that are not an input, textarea or a select. However, if the element is inside the <label> element that has an associated control, returns the value of the control.


isChecked

Added in: v1.14 locator.isChecked

返回该元素是否被检查。如果元素不是复选框或单选输入,则抛出此异常。

Returns whether the element is checked. Throws if the element is not a checkbox or radio input.

断言选中状态

如果你需要断言复选框已选中,请首选 expect(locator).toBeChecked() 以避免不稳定。详细信息请参见 断言指南

If you need to assert that checkbox is checked, prefer expect(locator).toBeChecked() to avoid flakiness. See assertions guide for more details.

用法

Usage

const checked = await page.getByRole('checkbox').isChecked();

参数

Arguments

最长时间(以毫秒为单位)。默认为 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.14 locator.isDisabled

返回该元素是否被禁用,与 enabled 相反。

Returns whether the element is disabled, the opposite of enabled.

断言禁用状态

如果你需要断言某个元素已禁用,请首选 expect(locator).toBeDisabled() 以避免不稳定。详细信息请参见 断言指南

If you need to assert that an element is disabled, prefer expect(locator).toBeDisabled() to avoid flakiness. See assertions guide for more details.

用法

Usage

const disabled = await page.getByRole('button').isDisabled();

参数

Arguments

最长时间(以毫秒为单位)。默认为 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.14 locator.isEditable

返回元素是否为 editable

Returns whether the element is editable.

断言可编辑状态

如果你需要断言某个元素是可编辑的,请首选 expect(locator).toBeEditable() 以避免不稳定。详细信息请参见 断言指南

If you need to assert that an element is editable, prefer expect(locator).toBeEditable() to avoid flakiness. See assertions guide for more details.

用法

Usage

const editable = await page.getByRole('textbox').isEditable();

参数

Arguments

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

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

返回

Returns


isEnabled

Added in: v1.14 locator.isEnabled

返回元素是否为 enabled

Returns whether the element is enabled.

断言启用状态

如果你需要断言某个元素已启用,请首选 expect(locator).toBeEnabled() 以避免不稳定。详细信息请参见 断言指南

If you need to assert that an element is enabled, prefer expect(locator).toBeEnabled() to avoid flakiness. See assertions guide for more details.

用法

Usage

const enabled = await page.getByRole('button').isEnabled();

参数

Arguments

最长时间(以毫秒为单位)。默认为 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.14 locator.isHidden

返回元素是否隐藏,与 visible 相反。

Returns whether the element is hidden, the opposite of visible.

断言可见性

如果你需要断言该元素已隐藏,请首选 expect(locator).toBeHidden() 以避免不稳定。详细信息请参见 断言指南

If you need to assert that element is hidden, prefer expect(locator).toBeHidden() to avoid flakiness. See assertions guide for more details.

用法

Usage

const hidden = await page.getByRole('button').isHidden();

参数

Arguments

Deprecated

This option is ignored. locator.isHidden() does not wait for the element to become hidden and returns immediately.

返回

Returns


isVisible

Added in: v1.14 locator.isVisible

返回元素是否为 visible

Returns whether the element is visible.

断言可见性

如果你需要断言该元素可见,请首选 expect(locator).toBeVisible() 以避免不稳定。详细信息请参见 断言指南

If you need to assert that element is visible, prefer expect(locator).toBeVisible() to avoid flakiness. See assertions guide for more details.

用法

Usage

const visible = await page.getByRole('button').isVisible();

参数

Arguments

Deprecated

This option is ignored. locator.isVisible() does not wait for the element to become visible and returns immediately.

返回

Returns


last

Added in: v1.14 locator.last

返回最后一个匹配元素的定位器。

Returns locator to the last matching element.

用法

Usage

const banana = await page.getByRole('listitem').last();

返回

Returns


locator

Added in: v1.14 locator.locator

该方法在定位器的子树中查找与指定选择器匹配的元素。它还接受过滤器选项,类似于 locator.filter() 方法。

The method finds an element matching the specified selector in the locator's subtree. It also accepts filter options, similar to locator.filter() method.

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

Learn more about locators.

用法

Usage

locator.locator(selectorOrLocator);
locator.locator(selectorOrLocator, options);

参数

Arguments

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

A selector or locator 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


nth

Added in: v1.14 locator.nth

返回第 n 个匹配元素的定位器。它是从零开始的,nth(0) 选择第一个元素。

Returns locator to the n-th matching element. It's zero based, nth(0) selects the first element.

用法

Usage

const banana = await page.getByRole('listitem').nth(2);

参数

Arguments

返回

Returns


or

Added in: v1.33 locator.or

创建一个与两个定位器中的任何一个匹配的定位器。

Creates a locator that matches either of the two locators.

用法

Usage

考虑这样一个场景:你想要单击 "新邮件" 按钮,但有时会显示安全设置对话框。在这种情况下,你可以等待 "新邮件" 按钮或对话框并进行相应操作。

Consider a scenario where you'd like to click on a "New email" button, but sometimes a security settings dialog shows up instead. In this case, you can wait for either a "New email" button, or a dialog and act accordingly.

const newEmail = page.getByRole('button', { name: 'New' });
const dialog = page.getByText('Confirm security settings');
await expect(newEmail.or(dialog)).toBeVisible();
if (await dialog.isVisible())
await page.getByRole('button', { name: 'Dismiss' }).click();
await newEmail.click();

参数

Arguments

要匹配的替代定位器。

Alternative locator to match.

返回

Returns


page

Added in: v1.19 locator.page

该定位器所属的页面。

A page this locator belongs to.

用法

Usage

locator.page();

返回

Returns


press

Added in: v1.14 locator.press

聚焦匹配元素并按下组合键。

Focuses the matching element and presses a combination of the keys.

用法

Usage

await page.getByRole('textbox').press('Backspace');

参数

Arguments

要按下的键的名称或要生成的字符,例如 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.

最长时间(以毫秒为单位)。默认为 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.

细节

Details

聚焦元素,然后使用 keyboard.down()keyboard.up()

Focuses the element, and then uses keyboard.down() and keyboard.up().

key 可以指定预期的 keyboardEvent.key 值或单个字符来生成文本。可以找到 key 值的超集 此处。键的示例有:

key can specify the intended keyboardEvent.key value or a single character to generate the text for. A superset of the key values can be found here. Examples of the keys are:

F1 - F12Digit0-Digit9KeyA-KeyZBackquoteMinusEqualBackslashBackspaceTabDeleteEscapeArrowDownEndEnterHomeInsertPageDownPageUpArrowRightArrowUp 等。

F1 - F12, Digit0- Digit9, KeyA- KeyZ, Backquote, Minus, Equal, Backslash, Backspace, Tab, Delete, Escape, ArrowDown, End, Enter, Home, Insert, PageDown, PageUp, ArrowRight, ArrowUp, etc.

还支持以下修改快捷方式:ShiftControlAltMetaShiftLeft

Following modification shortcuts are also supported: Shift, Control, Alt, Meta, ShiftLeft.

按住 Shift 将键入与大写 key 相对应的文本。

Holding down Shift will type the text that corresponds to the key in the upper case.

如果 key 是单个字符,则区分大小写,因此值 aA 将生成各自不同的文本。

If key is a single character, it is case-sensitive, so the values a and A will generate different respective texts.

还支持 key: "Control+o"key: "Control+Shift+T" 等快捷方式。当使用修饰符指定时,修饰符将被按下并在按下后续键的同时保持不变。

Shortcuts such as key: "Control+o" or key: "Control+Shift+T" are supported as well. When specified with the modifier, modifier is pressed and being held while the subsequent key is being pressed.


pressSequentially

Added in: v1.38 locator.pressSequentially
提示

在大多数情况下,你应该使用 locator.fill()。如果页面上有特殊的键盘处理,则只需一一按键即可。

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.

聚焦元素,然后为文本中的每个字符发送 keydownkeypress/inputkeyup 事件。

Focuses the element, and then sends a keydown, keypress/input, and keyup event for each character in the text.

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

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

用法

Usage

await locator.pressSequentially('Hello'); // Types instantly
await locator.pressSequentially('World', { delay: 100 }); // Types slower, like a user

在文本字段中输入内容然后提交表单的示例:

An example of typing into a text field and then submitting the form:

const locator = page.getByLabel('Password');
await locator.pressSequentially('my password');
await locator.press('Enter');

参数

Arguments

要按顺序压入焦点元素的字符串。

String of characters to sequentially press 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.

最长时间(以毫秒为单位)。默认为 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.


screenshot

Added in: v1.14 locator.screenshot

截取与定位器匹配的元素的屏幕截图。

Take a screenshot of the element matching the locator.

用法

Usage

await page.getByRole('link').screenshot();

禁用动画并将屏幕截图保存到文件中:

Disable animations and save screenshot to a file:

await page.getByRole('link').screenshot({ animations: 'disabled', path: 'link.png' });

参数

Arguments

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

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

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

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

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

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

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

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

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

    Defaults to "allow" that leaves animations untouched.

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    默认为 "device"

    Defaults to "device".

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

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

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

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

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

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

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

    指定截图类型,默认为 png

    Specify screenshot type, defaults to png.

返回

Returns

细节

Details

此方法捕获页面的屏幕截图,并将其裁剪为与定位器匹配的特定元素的大小和位置。如果该元素被其他元素覆盖,则在屏幕截图中实际上不会显示该元素。如果元素是可滚动容器,则屏幕截图上仅显示当前滚动的内容。

This method captures a screenshot of the page, clipped to the size and position of a particular element matching the locator. If the element is covered by other elements, it will not be actually visible on the screenshot. If the element is a scrollable container, only the currently scrolled content will be visible on the screenshot.

此方法等待 actionability 检查,然后将元素滚动到视图中,然后再进行屏幕截图。如果元素与 DOM 分离,该方法会抛出错误。

This method waits for the actionability checks, then scrolls element into view before taking a screenshot. If the element is detached from DOM, the method throws an error.

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

Returns the buffer with the captured screenshot.


scrollIntoViewIfNeeded

Added in: v1.14 locator.scrollIntoViewIfNeeded

此方法等待 actionability 检查,然后尝试将元素滚动到视图中,除非它按照 IntersectionObserverratio 的定义完全可见。

This method waits for actionability checks, then tries to scroll element into view, unless it is completely visible as defined by IntersectionObserver's ratio.

用法

Usage

await locator.scrollIntoViewIfNeeded();
await locator.scrollIntoViewIfNeeded(options);

参数

Arguments

最长时间(以毫秒为单位)。默认为 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.14 locator.selectOption

选择 <select> 中的一个或多个选项。

Selects option or options in <select>.

用法

Usage

<select multiple>
<option value="red">Red</div>
<option value="green">Green</div>
<option value="blue">Blue</div>
</select>
// single selection matching the value or label
element.selectOption('blue');

// single selection matching the label
element.selectOption({ label: 'Blue' });

// multiple selection for red, green and blue options
element.selectOption(['red', 'green', 'blue']);

参数

Arguments

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.

最长时间(以毫秒为单位)。默认为 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

细节

Details

此方法等待 actionability 检查,等待所有指定的选项都出现在 <select> 元素中并选择这些选项。

This method 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.


selectText

Added in: v1.14 locator.selectText

此方法等待 actionability 检查,然后聚焦该元素并选择其所有文本内容。

This method waits for actionability checks, then focuses the element and selects all its text content.

如果该元素位于具有关联 control<label> 元素内部,则改为聚焦并选择控件中的文本。

If the element is inside the <label> element that has an associated control, focuses and selects text in the control instead.

用法

Usage

await locator.selectText();
await locator.selectText(options);

参数

Arguments

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

Whether to bypass the actionability checks. Defaults to false.

最长时间(以毫秒为单位)。默认为 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.


setChecked

Added in: v1.15 locator.setChecked

设置复选框或单选元素的状态。

Set the state of a checkbox or a radio element.

用法

Usage

await page.getByRole('checkbox').setChecked(true);

参数

Arguments

是否选中或取消选中复选框。

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.

最长时间(以毫秒为单位)。默认为 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.

细节

Details

此方法通过执行以下步骤来检查或取消选中元素:

This method checks or unchecks an element by performing the following steps:

  1. 确保匹配的元素是复选框或单选输入。如果不是,该方法将抛出异常。

    Ensure that matched element is a checkbox or a radio input. If not, this method throws.

  2. 如果元素已经具有正确的检查状态,则此方法立即返回。

    If the element already has the right checked state, 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 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.


setInputFiles

Added in: v1.14 locator.setInputFiles

将一个或多个文件上传到 <input type=file>

Upload file or multiple files into <input type=file>.

用法

Usage

// Select one file
await page.getByLabel('Upload file').setInputFiles(path.join(__dirname, 'myfile.pdf'));

// Select multiple files
await page.getByLabel('Upload files').setInputFiles([
path.join(__dirname, 'file1.txt'),
path.join(__dirname, 'file2.txt'),
]);

// Remove all the selected files
await page.getByLabel('Upload file').setInputFiles([]);

// Upload buffer from memory
await page.getByLabel('Upload file').setInputFiles({
name: 'file.txt',
mimeType: 'text/plain',
buffer: Buffer.from('this is test')
});

参数

Arguments

文件名

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.

最长时间(以毫秒为单位)。默认为 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.

细节

Details

将文件输入的值设置为这些文件路径或文件。如果某些 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.

此方法期望 定位器 指向 输入元素。但是,如果该元素位于具有关联的 control<label> 元素内,则改为以控件为目标。

This method expects Locator to point to an input element. However, if the element is inside the <label> element that has an associated control, targets the control instead.


tap

Added in: v1.14 locator.tap

在与定位器匹配的元素上执行点击手势。

Perform a tap gesture on the element matching the locator.

用法

Usage

await locator.tap();
await locator.tap(options);

参数

Arguments

是否绕过 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.

最长时间(以毫秒为单位)。默认为 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.

细节

Details

此方法通过执行以下步骤来点击元素:

This method taps the element by performing the following steps:

  1. 等待 actionability 检查元素,除非设置了 force 选项。

    Wait for actionability checks on the element, unless force option is set.

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

    Scroll the element into view if needed.

  3. 使用 page.touchscreen 点击元素的中心,或指定的 position

    Use page.touchscreen to tap the center of the element, or the specified position.

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

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

如果该元素在操作过程中的任何时刻与 DOM 分离,则此方法会抛出异常。

If the element is detached from the DOM at any moment during the action, 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.

注意

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

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


textContent

Added in: v1.14 locator.textContent

返回 node.textContent

Returns the node.textContent.

断言文本

如果你需要在页面上断言文本,请首选 expect(locator).toHaveText() 以避免不稳定。详细信息请参见 断言指南

If you need to assert text on the page, prefer expect(locator).toHaveText() to avoid flakiness. See assertions guide for more details.

用法

Usage

await locator.textContent();
await locator.textContent(options);

参数

Arguments

最长时间(以毫秒为单位)。默认为 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


uncheck

Added in: v1.14 locator.uncheck

确保复选框或单选元素未选中。

Ensure that checkbox or radio element is unchecked.

用法

Usage

await page.getByRole('checkbox').uncheck();

参数

Arguments

是否绕过 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.

最长时间(以毫秒为单位)。默认为 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.

细节

Details

此方法通过执行以下步骤取消选中该元素:

This method unchecks the element by performing the following steps:

  1. 确保该元素是复选框或单选输入。如果不是,该方法将抛出异常。如果该元素已取消选中,则此方法立即返回。

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

  2. 等待 actionability 检查元素,除非设置了 force 选项。

    Wait for actionability checks on the element, unless force option is set.

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

    Scroll the element into view if needed.

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

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

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

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

  6. 确保该元素现在未被选中。如果不是,该方法将抛出异常。

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

如果该元素在操作过程中的任何时刻与 DOM 分离,则此方法会抛出异常。

If the element is detached from the DOM at any moment during the action, 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.


waitFor

Added in: v1.16 locator.waitFor

当定位器指定的元素满足 state 选项时返回。

Returns when element specified by locator satisfies the state option.

如果目标元素已经满足条件,该方法立即返回。否则,最多等待 timeout 毫秒,直到满足条件。

If target element already satisfies the condition, the method returns immediately. Otherwise, waits for up to timeout milliseconds until the condition is met.

用法

Usage

const orderSent = page.locator('#order-sent');
await orderSent.waitFor();

参数

Arguments

  • 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.

最长时间(以毫秒为单位)。默认为 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.


已弃用

Deprecated

elementHandle

Added in: v1.14 locator.elementHandle
劝阻

总是更喜欢使用 定位器 和网络断言而不是 ElementHandle,因为后者本质上是活泼的。

Always prefer using Locators and web assertions over ElementHandles because latter are inherently racy.

将给定定位器解析为第一个匹配的 DOM 元素。如果没有匹配的元素,则等待一个。如果多个元素与定位器匹配,则抛出异常。

Resolves given locator to the first matching DOM element. If there are no matching elements, waits for one. If multiple elements match the locator, throws.

用法

Usage

await locator.elementHandle();
await locator.elementHandle(options);

参数

Arguments

最长时间(以毫秒为单位)。默认为 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


elementHandles

Added in: v1.14 locator.elementHandles
劝阻

总是更喜欢使用 定位器 和网络断言而不是 ElementHandle,因为后者本质上是活泼的。

Always prefer using Locators and web assertions over ElementHandles because latter are inherently racy.

将给定定位器解析为所有匹配的 DOM 元素。如果没有匹配的元素,则返回一个空列表。

Resolves given locator to all matching DOM elements. If there are no matching elements, returns an empty list.

用法

Usage

await locator.elementHandles();

返回

Returns


type

Added in: v1.14 locator.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 事件。

Focuses the element, and then sends a keydown, keypress/input, and keyup event for each character in the text.

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

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

用法

Usage

参数

Arguments

要输入到焦点元素中的文本。

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.

最长时间(以毫秒为单位)。默认为 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.