Skip to main content

ElementHandle

ElementHandle 表示页内 DOM 元素。ElementHandles 可以使用 page.$() 方法创建。

¥ElementHandle represents an in-page DOM element. ElementHandles can be created with the page.$() method.

灰心

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

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

const hrefElement = await page.$('a');
await hrefElement.click();

ElementHandle 会阻止 DOM 元素进行垃圾回收,除非使用 jsHandle.dispose() 处理该句柄。当其原始框架被导航时,ElementHandles 会被自动处理。

¥ElementHandle prevents DOM element from garbage collection unless the handle is disposed with jsHandle.dispose(). ElementHandles are auto-disposed when their origin frame gets navigated.

ElementHandle 实例可以用作 page.$eval()page.evaluate() 方法中的参数。

¥ElementHandle instances can be used as an argument in page.$eval() and page.evaluate() methods.

Locator 和 ElementHandle 之间的区别在于 ElementHandle 指向特定元素,而 Locator 捕获如何检索元素的逻辑。

¥The difference between the Locator and ElementHandle is that the ElementHandle points to a particular element, while Locator captures the logic of how to retrieve an element.

在下面的示例中,句柄指向页面上的特定 DOM 元素。如果该元素更改文本或被 React 使用来渲染完全不同的组件,则句柄仍然指向该 DOM 元素。这可能会导致意外的行为。

¥In the example below, handle points to a particular DOM element on page. If that element changes text or is used by React to render an entirely different component, handle is still pointing to that very DOM element. This can lead to unexpected behaviors.

const handle = await page.$('text=Submit');
// ...
await handle.hover();
await handle.click();

使用定位器,每次使用 element 时,都会使用选择器在页面中定位最新的 DOM 元素。因此,在下面的代码片段中,底层 DOM 元素将被定位两次。

¥With the locator, every time the element is used, up-to-date DOM element is located in the page using the selector. So in the snippet below, underlying DOM element is going to be located twice.

const locator = page.getByText('Submit');
// ...
await locator.hover();
await locator.click();

方法

¥Methods

boundingBox

Added in: v1.8 elementHandle.boundingBox

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

¥This method returns the bounding box of the element, 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.

滚动会影响返回的边界框,与 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.

用法

¥Usage

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

返回

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


contentFrame

Added in: v1.8 elementHandle.contentFrame

返回引用 iframe 节点的元素句柄的内容框架,否则返回 null

¥Returns the content frame for element handles referencing iframe nodes, or null otherwise

用法

¥Usage

await elementHandle.contentFrame();

返回

¥Returns


ownerFrame

Added in: v1.8 elementHandle.ownerFrame

返回包含给定元素的框架。

¥Returns the frame containing the given element.

用法

¥Usage

await elementHandle.ownerFrame();

返回

¥Returns


waitForElementState

Added in: v1.8 elementHandle.waitForElementState

当元素满足 state 时返回。

¥Returns when the element satisfies the state.

根据 state 参数,此方法等待 actionability 检查之一通过。当元素在等待期间分离时,此方法将抛出,除非等待 "hidden" 状态。

¥Depending on the state parameter, this method waits for one of the actionability checks to pass. This method throws when the element is detached while waiting, unless waiting for the "hidden" state.

  • "visible" 等到元素为 visible

    ¥"visible" Wait until the element is visible.

  • "hidden" 等到元素为 不可见 或未附加。请注意,当元素分离时,等待隐藏不会抛出异常。

    ¥"hidden" Wait until the element is not visible or not attached. Note that waiting for hidden does not throw when the element detaches.

  • "stable" 等到元素同时为 visiblestable

    ¥"stable" Wait until the element is both visible and stable.

  • "enabled" 等到元素为 enabled

    ¥"enabled" Wait until the element is enabled.

  • "disabled" 等到元素为 未启用

    ¥"disabled" Wait until the element is not enabled.

  • "editable" 等到元素为 editable

    ¥"editable" Wait until the element is editable.

如果元素在 timeout 毫秒内不满足条件,则此方法将抛出异常。

¥If the element does not satisfy the condition for the timeout milliseconds, this method will throw.

用法

¥Usage

await elementHandle.waitForElementState(state);
await elementHandle.waitForElementState(state, options);

参数

¥Arguments

  • state "visible"|"hidden"|"stable"|"enabled"|"disabled"|"editable"#

    需要等待的状态,请参阅下文了解更多详细信息。

    ¥A state to wait for, see below for more details.

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


已弃用

¥Deprecated

$ {#}

Added in: v1.9 elementHandle.$
灰心

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

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

该方法在 ElementHandle 的子树中查找与指定选择器匹配的元素。如果没有元素与选择器匹配,则返回 null

¥The method finds an element matching the specified selector in the ElementHandle's subtree. If no elements match the selector, returns null.

用法

¥Usage

await elementHandle.$(selector);

参数

¥Arguments

要查询的选择器。

¥A selector to query for.

返回

¥Returns


$$

Added in: v1.9 elementHandle.$$
灰心

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

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

该方法在 ElementHandle 子树中查找与指定选择器匹配的所有元素。如果没有元素与选择器匹配,则返回空数组。

¥The method finds all elements matching the specified selector in the ElementHandles subtree. If no elements match the selector, returns empty array.

用法

¥Usage

await elementHandle.$$(selector);

参数

¥Arguments

要查询的选择器。

¥A selector to query for.

返回

¥Returns


$eval

Added in: v1.9 elementHandle.$eval
灰心

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

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

返回 pageFunction 的返回值。

¥Returns the return value of pageFunction.

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

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

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

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

用法

¥Usage

const tweetHandle = await page.$('.tweet');
expect(await tweetHandle.$eval('.like', node => node.innerText)).toBe('100');
expect(await tweetHandle.$eval('.retweets', node => node.innerText)).toBe('10');

参数

¥Arguments

要查询的选择器。

¥A selector to query for.

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

¥Function to be evaluated in the page context.

传递给 pageFunction 的可选参数。

¥Optional argument to pass to pageFunction.

返回

¥Returns


$$eval

Added in: v1.9 elementHandle.$$eval
灰心

在大多数情况下,locator.evaluateAll()、其他 Locator 辅助方法和 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.

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

¥The method finds all elements matching the specified selector in the ElementHandle's subtree and passes an array of matched elements as a first argument to pageFunction.

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

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

用法

¥Usage

<div class="feed">
<div class="tweet">Hello!</div>
<div class="tweet">Hi!</div>
</div>
const feedHandle = await page.$('.feed');
expect(await feedHandle.$$eval('.tweet', nodes =>
nodes.map(n => n.innerText))).toEqual(['Hello!', 'Hi!'],
);

参数

¥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 elementHandle.check
灰心

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

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

此方法通过执行以下步骤来检查元素:

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

用法

¥Usage

await elementHandle.check();
await elementHandle.check(options);

参数

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

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

返回

¥Returns


click

Added in: v1.8 elementHandle.click
灰心

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

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

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

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

用法

¥Usage

await elementHandle.click();
await elementHandle.click(options);

参数

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

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

返回

¥Returns


dblclick

Added in: v1.8 elementHandle.dblclick
灰心

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

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

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

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

注意

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

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

用法

¥Usage

await elementHandle.dblclick();
await elementHandle.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.

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

返回

¥Returns


dispatchEvent

Added in: v1.8 elementHandle.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 elementHandle.dispatchEvent('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 elementHandle.dispatchEvent('dragstart', { dataTransfer });

参数

¥Arguments

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

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

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

¥Optional event-specific initialization properties.

返回

¥Returns


fill

Added in: v1.8 elementHandle.fill
灰心

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

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

该方法等待 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().

用法

¥Usage

await elementHandle.fill(value);
await elementHandle.fill(value, options);

参数

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

返回

¥Returns


focus

Added in: v1.8 elementHandle.focus
灰心

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

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

对元素调用 focus

¥Calls focus on the element.

用法

¥Usage

await elementHandle.focus();

返回

¥Returns


getAttribute

Added in: v1.8 elementHandle.getAttribute
灰心

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

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

返回元素属性值。

¥Returns element attribute value.

用法

¥Usage

await elementHandle.getAttribute(name);

参数

¥Arguments

要获取其值的属性名称。

¥Attribute name to get the value for.

返回

¥Returns


hover

Added in: v1.8 elementHandle.hover
灰心

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

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

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

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

用法

¥Usage

await elementHandle.hover();
await elementHandle.hover(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.

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

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

返回

¥Returns


innerHTML

Added in: v1.8 elementHandle.innerHTML
灰心

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

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

返回 element.innerHTML

¥Returns the element.innerHTML.

用法

¥Usage

await elementHandle.innerHTML();

返回

¥Returns


innerText

Added in: v1.8 elementHandle.innerText
灰心

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

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

返回 element.innerText

¥Returns the element.innerText.

用法

¥Usage

await elementHandle.innerText();

返回

¥Returns


inputValue

Added in: v1.13 elementHandle.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 elementHandle.inputValue();
await elementHandle.inputValue(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


isChecked

Added in: v1.8 elementHandle.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 elementHandle.isChecked();

返回

¥Returns


isDisabled

Added in: v1.8 elementHandle.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 elementHandle.isDisabled();

返回

¥Returns


isEditable

Added in: v1.8 elementHandle.isEditable
灰心

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

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

返回元素是否为 editable

¥Returns whether the element is editable.

用法

¥Usage

await elementHandle.isEditable();

返回

¥Returns


isEnabled

Added in: v1.8 elementHandle.isEnabled
灰心

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

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

返回元素是否为 enabled

¥Returns whether the element is enabled.

用法

¥Usage

await elementHandle.isEnabled();

返回

¥Returns


isHidden

Added in: v1.8 elementHandle.isHidden
灰心

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

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

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

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

用法

¥Usage

await elementHandle.isHidden();

返回

¥Returns


isVisible

Added in: v1.8 elementHandle.isVisible
灰心

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

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

返回元素是否为 visible

¥Returns whether the element is visible.

用法

¥Usage

await elementHandle.isVisible();

返回

¥Returns


press

Added in: v1.8 elementHandle.press
灰心

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

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

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

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

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

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

F1 - F12Digit0-Digit9KeyA-KeyZBackquoteMinusEqualBackslashBackspaceTabDeleteEscapeArrowDownEndEnterHomeInsertPageDownPageUpArrowRightArrowUp 等。

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

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

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

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

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

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

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

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

¥Shortcuts such as key: "Control+o", key: "Control++ 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 elementHandle.press(key);
await elementHandle.press(key, options);

参数

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

返回

¥Returns


screenshot

Added in: v1.8 elementHandle.screenshot
灰心

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

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

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

¥This method captures a screenshot of the page, clipped to the size and position of this particular element. 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.

用法

¥Usage

await elementHandle.screenshot();
await elementHandle.screenshot(options);

参数

¥Arguments

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

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

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

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

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

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

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

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

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

    ¥Defaults to "allow" that leaves animations untouched.

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

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

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

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

指定截取屏幕截图时应屏蔽的定位器。被遮罩的元素将被一个粉色框 #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


scrollIntoViewIfNeeded

Added in: v1.8 elementHandle.scrollIntoViewIfNeeded
灰心

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

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

此方法等待 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.

elementHandle 未指向 Document 或 ShadowRoot 的元素 connected 时抛出。

¥Throws when elementHandle does not point to an element connected to a Document or a ShadowRoot.

用法

¥Usage

await elementHandle.scrollIntoViewIfNeeded();
await elementHandle.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.

返回

¥Returns


selectOption

Added in: v1.8 elementHandle.selectOption
灰心

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

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

此方法等待 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.

用法

¥Usage

// Single selection matching the value or label
handle.selectOption('blue');

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

// multiple selection
handle.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


selectText

Added in: v1.8 elementHandle.selectText
灰心

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

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

此方法等待 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 elementHandle.selectText();
await elementHandle.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.

返回

¥Returns


setChecked

Added in: v1.15 elementHandle.setChecked
灰心

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

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

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

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

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

    ¥Ensure that 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.

用法

¥Usage

await elementHandle.setChecked(checked);
await elementHandle.setChecked(checked, options);

参数

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

返回

¥Returns


setInputFiles

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

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

¥This method expects ElementHandle 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 elementHandle.setInputFiles(files);
await elementHandle.setInputFiles(files, options);

参数

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

返回

¥Returns


tap

Added in: v1.8 elementHandle.tap
灰心

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

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

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

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

注意

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

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

用法

¥Usage

await elementHandle.tap();
await elementHandle.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.

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

返回

¥Returns


textContent

Added in: v1.8 elementHandle.textContent
灰心

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

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

返回 node.textContent

¥Returns the node.textContent.

用法

¥Usage

await elementHandle.textContent();

返回

¥Returns


type

Added in: v1.8 elementHandle.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,请使用 elementHandle.press()

¥To press a special key, like Control or ArrowDown, use elementHandle.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.

返回

¥Returns


uncheck

Added in: v1.8 elementHandle.uncheck
灰心

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

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

此方法通过执行以下步骤来检查元素:

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

用法

¥Usage

await elementHandle.uncheck();
await elementHandle.uncheck(options);

参数

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

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

返回

¥Returns


waitForSelector

Added in: v1.8 elementHandle.waitForSelector
灰心

请改用断言可见性的 Web 断言或基于定位器的 locator.waitFor()

¥Use web assertions that assert visibility or a locator-based locator.waitFor() instead.

当选择器满足 state 选项时,返回选择器指定的元素。如果等待 hiddendetached,则返回 null

¥Returns element specified by selector when it satisfies state option. Returns null if waiting for hidden or detached.

等待相对于元素句柄的 selector 满足 state 选项(从 dom 中出现/消失,或者变得可见/隐藏)。如果在调用方法 selector 时已经满足条件,则该方法将立即返回。如果选择器在 timeout 毫秒内不满足条件,该函数将抛出异常。

¥Wait for the selector relative to the element handle 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

await page.setContent(`<div><span></span></div>`);
const div = await page.$('div');
// Waiting for the 'span' selector relative to the div.
const span = await div.waitForSelector('span', { state: 'attached' });
注意

此方法不适用于跨导航,请改用 page.waitForSelector()

¥This method does not work across navigations, use page.waitForSelector() instead.

参数

¥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.15#

如果为 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