Skip to main content

ElementHandle

ElementHandle 表示页面中的 DOM 元素。可以使用 Page.querySelector() 方法创建 ElementHandle。

🌐 ElementHandle represents an in-page DOM element. ElementHandles can be created with the Page.querySelector() method.

Discouraged

不建议使用 ElementHandle,请改用 Locator 对象和网页优先的断言。

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

ElementHandle hrefElement = page.querySelector("a");
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.evalOnSelector()Page.evaluate() 方法的参数使用。

🌐 ElementHandle instances can be used as an argument in Page.evalOnSelector() 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.

在下面的例子中,handle 指向页面上的一个特定 DOM 元素。如果该元素的文本发生变化,或者被 React 用来渲染一个完全不同的组件,handle 仍然指向那个 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.

ElementHandle handle = page.querySelector("text=Submit");
handle.hover();
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.

Locator locator = page.getByText("Submit");
locator.hover();
locator.click();

方法

🌐 Methods

boundingBox

Added before v1.9 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.

用法

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

返回

  • null | BoundingBox#
    • x double

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

    • y double

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

    • width double

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

    • height double

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


contentFrame

Added before v1.9 elementHandle.contentFrame

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

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

用法

ElementHandle.contentFrame();

返回


ownerFrame

Added before v1.9 elementHandle.ownerFrame

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

🌐 Returns the frame containing the given element.

用法

ElementHandle.ownerFrame();

返回


waitForElementState

Added before v1.9 elementHandle.waitForElementState

当元素满足状态时返回。

🌐 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" 等待元素可见(../actionability.mdx#visible)。
  • "hidden" 等待元素不可见或不再附加。注意,当元素被移除时,等待隐藏不会抛出异常。
  • "stable" 等待元素同时 可见稳定
  • "enabled" 等待元素被 启用
  • "disabled" 等到元素不可用时。
  • "editable" 等待元素可编辑

如果元素不满足 setTimeout 毫秒的条件,此方法将抛出异常。

🌐 If the element does not satisfy the condition for the setTimeout milliseconds, this method will throw.

用法

ElementHandle.waitForElementState(state);
ElementHandle.waitForElementState(state, options);

参数

  • state enum ElementState { VISIBLE, HIDDEN, STABLE, ENABLED, DISABLED, EDITABLE }#

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

  • options ElementHandle.WaitForElementStateOptions (optional)

返回


已弃用

🌐 Deprecated

check

Added before v1.9 elementHandle.check
Discouraged

请改为使用基于定位器的 Locator.check()。了解更多关于 定位器 的信息。

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

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

🌐 This method checks the element by performing the following steps:

  1. 确保该元素是复选框或单选按钮输入。如果不是,该方法会抛出异常。如果元素已经被选中,该方法会立即返回。
  2. 等待对该元素进行[可作性](../actionability.mdx)检查,除非设置了[setForce](/api/class-elementhandle.mdx#element-handle-check-option-force)选项。
  3. 如果需要,将元素滚动到视图中。
  4. 使用 Page.mouse() 在元素中心点击。
  5. 确保该元素现在已被选中。如果没有,该方法会抛出异常。

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

🌐 If the element is detached from the DOM at any moment during the action, this method throws.

当所有步骤在指定的 setTimeout 内未完成时,该方法会抛出 TimeoutError。传入零超时可禁用此功能。

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

用法

ElementHandle.check();
ElementHandle.check(options);

参数

  • options ElementHandle.CheckOptions (optional)
    • setForce boolean (optional)#

      是否绕过 可操作性 检查。默认值为 false

    • setNoWaitAfter boolean (optional)#

      :::警告[已弃用] 这个选项没有效果。 :::

      此选项无效。

    • setPosition Position (optional) Added in: v1.11#

      相对于元素内边距盒左上角使用的一个点。如果未指定,则使用元素的某个可见点。

    • setTimeout double (optional)#

      最长时间(以毫秒为单位)。默认值为 30000(30 秒)。传入 0 可禁用超时。默认值可以通过使用 BrowserContext.setDefaultTimeout()Page.setDefaultTimeout() 方法进行更改。

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

      设置后,该方法仅执行 可操作性 检查,而跳过实际操作。默认为 false。在不执行操作的情况下,等待元素准备好进行操作时非常有用。

返回


click

Added before v1.9 elementHandle.click
Discouraged

请改为使用基于定位器的 Locator.click()。了解更多关于 定位器 的信息。

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

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

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

  1. 等待元素的 actionability 检查,除非设置了 setForce 选项。
  2. 如果需要,将元素滚动到视图中。
  3. 使用 Page.mouse() 点击元素中心,或使用指定的 setPosition
  4. 等待已启动的导航成功或失败,除非设置了 setNoWaitAfter 选项。

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

🌐 If the element is detached from the DOM at any moment during the action, this method throws.

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

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

用法

ElementHandle.click();
ElementHandle.click(options);

参数

  • options ElementHandle.ClickOptions (optional)
    • setButton enum MouseButton { LEFT, RIGHT, MIDDLE } (optional)#

      默认为 left

    • setClickCount int (optional)#

      默认为 1。请参阅 UIEvent.detail

    • setDelay double (optional)#

      mousedownmouseup 之间的等待时间,以毫秒为单位。默认值为 0。

    • setForce boolean (optional)#

      是否绕过 可操作性 检查。默认值为 false

    • setModifiers List<enum KeyboardModifier { ALT, CONTROL, CONTROLORMETA, META, SHIFT }> (optional)#

      要按下的修饰键。确保在操作过程中仅按下这些修饰键,然后恢复当前的修饰键。如果未指定,则使用当前按下的修饰键。“ControlOrMeta”在 Windows 和 Linux 上对应“Control”,在 macOS 上对应“Meta”。

    • setNoWaitAfter boolean (optional)#

      已弃用

      该选项将来默认值为 true

      发起导航的操作会等待这些导航发生并且页面开始加载。你可以通过设置此标志选择不等待。你通常只有在特殊情况下(例如导航到无法访问的页面)才需要此选项。默认值为 false

    • setPosition Position (optional)#

      相对于元素内边距盒左上角使用的一个点。如果未指定,则使用元素的某个可见点。

    • setSteps int (optional) Added in: v1.57#

      默认为1。发送 n 个插值的 mousemove 事件,以表示从 Playwright 当前光标位置到指定目的地的移动。当设置为1时,在目标位置只发出一个 mousemove 事件。

    • setTimeout double (optional)#

      最长时间(以毫秒为单位)。默认值为 30000(30 秒)。传入 0 可禁用超时。默认值可以通过使用 BrowserContext.setDefaultTimeout()Page.setDefaultTimeout() 方法进行更改。

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

      设置后,该方法仅执行 可操作性 检查,而跳过实际操作。默认为 false。在不执行操作的情况下,等待元素准备好进行操作时非常有用。

返回


dblclick

Added before v1.9 elementHandle.dblclick
Discouraged

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

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

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

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

  1. 等待元素的 actionability 检查,除非设置了 setForce 选项。
  2. 如果需要,将元素滚动到视图中。
  3. 使用 Page.mouse() 在元素中心或指定的 setPosition 处双击。

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

🌐 If the element is detached from the DOM at any moment during the action, this method throws.

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

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

note

elementHandle.dblclick() 触发两个 click 事件和一个 dblclick 事件。

用法

ElementHandle.dblclick();
ElementHandle.dblclick(options);

参数

  • options ElementHandle.DblclickOptions (optional)
    • setButton enum MouseButton { LEFT, RIGHT, MIDDLE } (optional)#

      默认为 left

    • setDelay double (optional)#

      mousedownmouseup 之间的等待时间,以毫秒为单位。默认值为 0。

    • setForce boolean (optional)#

      是否绕过 可操作性 检查。默认值为 false

    • setModifiers List<enum KeyboardModifier { ALT, CONTROL, CONTROLORMETA, META, SHIFT }> (optional)#

      要按下的修饰键。确保在操作过程中仅按下这些修饰键,然后恢复当前的修饰键。如果未指定,则使用当前按下的修饰键。“ControlOrMeta”在 Windows 和 Linux 上对应“Control”,在 macOS 上对应“Meta”。

    • setNoWaitAfter boolean (optional)#

      :::警告[已弃用] 这个选项没有效果。

此选项无效。

  • setPosition Position (optional)#

    相对于元素内边距盒左上角使用的一个点。如果未指定,则使用元素的某个可见点。

  • setSteps int (optional) Added in: v1.57#

    默认为1。发送 n 个插值的 mousemove 事件,以表示从 Playwright 当前光标位置到指定目的地的移动。当设置为1时,在目标位置只发出一个 mousemove 事件。

  • setTimeout double (optional)#

    最长时间(以毫秒为单位)。默认值为 30000(30 秒)。传入 0 可禁用超时。默认值可以通过使用 BrowserContext.setDefaultTimeout()Page.setDefaultTimeout() 方法进行更改。

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

    设置后,该方法仅执行 可操作性 检查,而跳过实际操作。默认为 false。在不执行操作的情况下,等待元素准备好进行操作时非常有用。

返回


dispatchEvent

Added before v1.9 elementHandle.dispatchEvent
Discouraged

请改用基于定位器的 Locator.dispatchEvent()。了解更多关于 定位器 的信息。

🌐 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().

用法

elementHandle.dispatchEvent("click");

在底层,它会根据给定的 type 创建一个事件实例,使用 eventInit 属性初始化该事件,并在元素上分发它。事件类型是 composedcancelable,默认情况下会冒泡。

🌐 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
JSHandle dataTransfer = page.evaluateHandle("() => new DataTransfer()");
Map<String, Object> arg = new HashMap<>();
arg.put("dataTransfer", dataTransfer);
elementHandle.dispatchEvent("dragstart", arg);

参数

  • type String#

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

  • eventInit EvaluationArgument (optional)#

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

返回


evalOnSelector

Added in: v1.9 elementHandle.evalOnSelector
Discouraged

此方法不会等待元素通过可操作性检查,因此可能导致测试不稳定。建议使用 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.

返回 expression 的返回值。

🌐 Returns the return value of expression.

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

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

如果 expression 返回一个 Promise,那么 ElementHandle.evalOnSelector() 会等待该 promise 解决并返回其值。

🌐 If expression returns a Promise, then ElementHandle.evalOnSelector() would wait for the promise to resolve and return its value.

用法

ElementHandle tweetHandle = page.querySelector(".tweet");
assertEquals("100", tweetHandle.evalOnSelector(".like", "node => node.innerText"));
assertEquals("10", tweetHandle.evalOnSelector(".retweets", "node => node.innerText"));

参数

  • selector String#

    要查询的选择器。

  • expression String#

    将在浏览器上下文中求值的 JavaScript 表达式。如果表达式求值为一个函数,该函数将被自动调用。

  • arg EvaluationArgument (optional)#

    可选参数,传递给 expression

返回


evalOnSelectorAll

Added in: v1.9 elementHandle.evalOnSelectorAll
Discouraged

在大多数情况下,Locator.evaluateAll()、其他 Locator 辅助方法以及以网页为先的断言效果更好。

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

返回 expression 的返回值。

🌐 Returns the return value of expression.

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

🌐 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 expression.

如果 expression 返回一个 Promise,那么 ElementHandle.evalOnSelectorAll() 会等待该 Promise 解决并返回其值。

🌐 If expression returns a Promise, then ElementHandle.evalOnSelectorAll() would wait for the promise to resolve and return its value.

用法

<div class="feed">
<div class="tweet">Hello!</div>
<div class="tweet">Hi!</div>
</div>
ElementHandle feedHandle = page.querySelector(".feed");
assertEquals(Arrays.asList("Hello!", "Hi!"), feedHandle.evalOnSelectorAll(".tweet", "nodes => nodes.map(n => n.innerText)"));

参数

  • selector String#

    要查询的选择器。

  • expression String#

    将在浏览器上下文中求值的 JavaScript 表达式。如果表达式求值为一个函数,该函数将被自动调用。

  • arg EvaluationArgument (optional)#

    可选参数,传递给 expression

返回


fill

Added before v1.9 elementHandle.fill
Discouraged

请改为使用基于定位器的 Locator.fill()。了解更多关于 定位器 的信息。

🌐 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] 元素,该方法会抛出错误。不过,如果该元素位于具有关联 控件<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().

用法

ElementHandle.fill(value);
ElementHandle.fill(value, options);

参数

  • value String#

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

  • options ElementHandle.FillOptions (optional)

返回


focus

Added before v1.9 elementHandle.focus
Discouraged

请改为使用基于定位器的 Locator.focus()。了解更多关于 定位器 的信息。

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

对元素调用[focus](https://web.nodejs.cn/en-US/docs/Web/API/HTMLElement/focus)。

🌐 Calls focus on the element.

用法

ElementHandle.focus();

返回


getAttribute

Added before v1.9 elementHandle.getAttribute
Discouraged

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

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

返回元素属性值。

🌐 Returns element attribute value.

用法

ElementHandle.getAttribute(name);

参数

  • name String#

    要获取其值的属性名称。

返回


hover

Added before v1.9 elementHandle.hover
Discouraged

请改为使用基于定位器的 Locator.hover()。了解更多关于 定位器 的信息。

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

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

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

  1. 等待对该元素进行[可作性](../actionability.mdx)检查,除非设置了[setForce](/api/class-elementhandle.mdx#element-handle-hover-option-force)选项。
  2. 如果需要,将元素滚动到视图中。
  3. 使用 Page.mouse() 将鼠标悬停在元素的中心,或指定的 setPosition 位置。

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

🌐 If the element is detached from the DOM at any moment during the action, this method throws.

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

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

用法

ElementHandle.hover();
ElementHandle.hover(options);

参数

  • options ElementHandle.HoverOptions (optional)
    • setForce boolean (optional)#

      是否绕过 可操作性 检查。默认值为 false

    • setModifiers List<enum KeyboardModifier { ALT, CONTROL, CONTROLORMETA, META, SHIFT }> (optional)#

      要按下的修饰键。确保在操作过程中仅按下这些修饰键,然后恢复当前的修饰键。如果未指定,则使用当前按下的修饰键。“ControlOrMeta”在 Windows 和 Linux 上对应“Control”,在 macOS 上对应“Meta”。

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

      :::警告[已弃用] 这个选项没有效果。 :::

      此选项无效。

    • setPosition Position (optional)#

      相对于元素内边距盒左上角使用的一个点。如果未指定,则使用元素的某个可见点。

    • setTimeout double (optional)#

      最长时间(以毫秒为单位)。默认值为 30000(30 秒)。传入 0 可禁用超时。默认值可以通过使用 BrowserContext.setDefaultTimeout()Page.setDefaultTimeout() 方法进行更改。

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

      设置后,该方法仅执行 可操作性 检查,而跳过实际操作。默认为 false。在不执行操作的情况下,等待元素准备好进行操作时非常有用。

返回


innerHTML

Added before v1.9 elementHandle.innerHTML
Discouraged

请改为使用基于定位器的 Locator.innerHTML()。阅读更多关于 定位器 的内容。

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

返回 element.innerHTML

🌐 Returns the element.innerHTML.

用法

ElementHandle.innerHTML();

返回


innerText

Added before v1.9 elementHandle.innerText
Discouraged

请改为使用基于定位器的 Locator.innerText()。阅读更多关于 定位器 的内容。

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

返回 element.innerText

🌐 Returns the element.innerText.

用法

ElementHandle.innerText();

返回


inputValue

Added in: v1.13 elementHandle.inputValue
Discouraged

请改为使用基于定位器的 Locator.inputValue()。阅读更多关于 定位器 的信息。

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

针对非输入元素会抛出异常。然而,如果该元素位于具有关联控件<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.

用法

ElementHandle.inputValue();
ElementHandle.inputValue(options);

参数

返回


isChecked

Added before v1.9 elementHandle.isChecked
Discouraged

请改为使用基于定位器的 Locator.isChecked()。阅读更多关于 定位器 的内容。

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

用法

ElementHandle.isChecked();

返回


isDisabled

Added before v1.9 elementHandle.isDisabled
Discouraged

请改为使用基于定位器的 Locator.isDisabled()。阅读更多关于 定位器 的信息。

🌐 Use locator-based Locator.isDisabled() instead. Read more about locators.

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

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

用法

ElementHandle.isDisabled();

返回


isEditable

Added before v1.9 elementHandle.isEditable
Discouraged

请改为使用基于定位器的 Locator.isEditable()。阅读更多关于 定位器 的内容。

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

返回元素是否可编辑

🌐 Returns whether the element is editable.

用法

ElementHandle.isEditable();

返回


isEnabled

Added before v1.9 elementHandle.isEnabled
Discouraged

请改为使用基于定位器的 Locator.isEnabled()。阅读更多关于 定位器 的内容。

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

返回元素是否已启用

🌐 Returns whether the element is enabled.

用法

ElementHandle.isEnabled();

返回


isHidden

Added before v1.9 elementHandle.isHidden
Discouraged

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

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

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

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

用法

ElementHandle.isHidden();

返回


isVisible

Added before v1.9 elementHandle.isVisible
Discouraged

请改为使用基于定位器的 Locator.isVisible()。阅读更多关于 定位器 的内容。

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

返回元素是否可见

🌐 Returns whether the element is visible.

用法

ElementHandle.isVisible();

返回


press

Added before v1.9 elementHandle.press
Discouraged

请改为使用基于定位器的 Locator.press()。了解更多关于 定位器 的信息。

🌐 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 值的超集可以在 这里 找到。键的示例有:

F1 - F12Digit0- Digit9KeyA- KeyZBackquoteMinusEqualBackslashBackspaceTabDeleteEscapeArrowDownEndEnterHomeInsertPageDownPageUpArrowRightArrowUp,等等。

以下修改快捷方式也受支持:ShiftControlAltMetaShiftLeftControlOrMeta

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

按住 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.

用法

ElementHandle.press(key);
ElementHandle.press(key, options);

参数

  • key String#

    输入按键名称或生成字符名称,如“ArrowLeft”或“a”。

  • options ElementHandle.PressOptions (optional)

    • setDelay double (optional)#

      keydownkeyup 之间的等待时间,以毫秒为单位。默认值为 0。

    • setNoWaitAfter boolean (optional)#

      已弃用

      该选项将来默认值为 true

      发起导航的操作会等待这些导航发生并且页面开始加载。你可以通过设置此标志选择不等待。你通常只有在特殊情况下(例如导航到无法访问的页面)才需要此选项。默认值为 false

    • setTimeout double (optional)#

      最长时间(以毫秒为单位)。默认值为 30000(30 秒)。传入 0 可禁用超时。默认值可以通过使用 BrowserContext.setDefaultTimeout()Page.setDefaultTimeout() 方法进行更改。

返回


querySelector

Added in: v1.9 elementHandle.querySelector
Discouraged

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

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

用法

ElementHandle.querySelector(selector);

参数

  • selector String#

    要查询的选择器。

返回


querySelectorAll

Added in: v1.9 elementHandle.querySelectorAll
Discouraged

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

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

用法

ElementHandle.querySelectorAll(selector);

参数

  • selector String#

    要查询的选择器。

返回


screenshot

Added before v1.9 elementHandle.screenshot
Discouraged

请改为使用基于定位器的 Locator.screenshot()。阅读更多关于 定位器 的内容。

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

此方法会等待可操作性检查,然后将元素滚动到可视区域后再截图。如果元素已从 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.

用法

ElementHandle.screenshot();
ElementHandle.screenshot(options);

参数

  • options ElementHandle.ScreenshotOptions (optional)
    • setAnimations enum ScreenshotAnimations { DISABLED, ALLOW } (optional)#

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

      • 有限动画会被快进至完成,因此它们会触发 transitionend 事件。
      • 无限动画被取消到初始状态,然后在屏幕截图后播放。

      默认值为 "allow",不会改变动画。

    • setCaret enum ScreenshotCaret { HIDE, INITIAL } (optional)#

      当设置为 "hide" 时,截图将隐藏文本光标。当设置为 "initial" 时,文本光标的行为不会改变。默认值为 "hide"

    • setMask List<Locator> (optional)#

      指定在截图时应被遮罩的定位器。被遮罩的元素将被一个粉红色框 #FF00FF 覆盖(可通过 setMaskColor 自定义),完全覆盖其边界框。该遮罩也会应用于不可见元素,参见 仅匹配可见元素 以禁用此功能。

    • setMaskColor String (optional) Added in: v1.35#

      指定被遮罩元素的覆盖框颜色,使用 CSS 颜色格式。默认颜色是粉色 #FF00FF

    • setOmitBackground boolean (optional)#

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

    • setPath Path (optional)#

      保存图片的文件路径。截图类型将根据文件扩展名推断。如果 setPath 是相对路径,则相对于当前工作目录解析。如果未提供路径,图片将不会保存到磁盘。

    • setQuality int (optional)#

      图片质量,范围为0-100。不适用于 png 图片。

    • setScale enum ScreenshotScale { CSS, DEVICE } (optional)#

      当设置为 "css" 时,截图将每个页面的 CSS 像素对应一个像素。对于高分辨率设备,这将保持截图文件较小。使用 "device" 选项将每个设备像素对应一个像素,因此高分辨率设备的截图将会大两倍甚至更多。

      默认为 "device"

    • setStyle String (optional) Added in: v1.41#

      在截图时要应用的样式表文本。在这里,你可以隐藏动态元素,使元素不可见或更改它们的属性,以帮助你创建可重复的截图。此样式表可以穿透 Shadow DOM 并应用于内部框架。

    • setTimeout double (optional)#

      最长时间(以毫秒为单位)。默认值为 30000(30 秒)。传入 0 可禁用超时。默认值可以通过使用 BrowserContext.setDefaultTimeout()Page.setDefaultTimeout() 方法进行更改。

    • setType enum ScreenshotType { PNG, JPEG } (optional)#

      指定截图类型,默认为 png

返回


scrollIntoViewIfNeeded

Added before v1.9 elementHandle.scrollIntoViewIfNeeded
Discouraged

请改用基于定位器的 Locator.scrollIntoViewIfNeeded()。阅读更多关于 定位器 的内容。

🌐 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 未指向与文档或 ShadowRoot 连接 的元素时会抛出异常。

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

查看滚动以了解其他滚动方式。

🌐 See scrolling for alternative ways to scroll.

用法

ElementHandle.scrollIntoViewIfNeeded();
ElementHandle.scrollIntoViewIfNeeded(options);

参数

返回


selectOption

Added before v1.9 elementHandle.selectOption
Discouraged

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

🌐 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> 元素,此方法将抛出错误。然而,如果该元素位于具有关联 控件<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.

用法

// Single selection matching the value or label
handle.selectOption("blue");
// single selection matching the label
handle.selectOption(new SelectOption().setLabel("Blue"));
// multiple selection
handle.selectOption(new String[] {"red", "green", "blue"});

参数

  • values null | String | ElementHandle | String[] | SelectOption | ElementHandle[] | SelectOption[]#

    • setValue String (optional)

      比赛由“option.value”统计。可选。

    • setLabel String (optional)

      option.label 匹配。可选。

    • setIndex int (optional)

      按索引匹配。可选。

    可选择的选项。如果 <select> 拥有 multiple 属性,则所有匹配的选项都会被选中,否则只会选择与传入选项之一匹配的第一个选项。字符串值会同时匹配值和标签。如果所有指定的属性都匹配,则该选项被视为匹配。

  • options ElementHandle.SelectOptionOptions (optional)

返回


selectText

Added before v1.9 elementHandle.selectText
Discouraged

请改为使用基于定位器的 Locator.selectText()。阅读更多关于 定位器 的内容。

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

该方法会等待可操作性检查,然后聚焦元素并选择其所有文本内容。

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

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

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

用法

ElementHandle.selectText();
ElementHandle.selectText(options);

参数

返回


setChecked

Added in: v1.15 elementHandle.setChecked
Discouraged

请改为使用基于定位器的 Locator.setChecked()。阅读更多关于 定位器 的内容。

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

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

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

  1. 确保元素是复选框或单选按钮输入。如果不是,该方法将抛出异常。
  2. 如果元素已经具有正确的检查状态,则此方法立即返回。
  3. 等待对匹配元素的 actionability 检查,除非已设置 setForce 选项。如果在检查期间元素被分离,整个操作将被重试。
  4. 如果需要,将元素滚动到视图中。
  5. 使用 Page.mouse() 在元素中心点击。
  6. 确保该元素现在已被选中或未被选中。如果没有,则此方法会抛出异常。

当所有步骤合并未在指定的[setTimeout](/api/class-elementhandle.mdx#element-handle-set-checked-option-timeout)内完成时,该方法会抛出TimeoutError。通过零超时则禁用。

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

用法

ElementHandle.setChecked(checked);
ElementHandle.setChecked(checked, options);

参数

  • checked boolean#

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

  • options ElementHandle.SetCheckedOptions (optional)

    • setForce boolean (optional)#

      是否绕过 可操作性 检查。默认值为 false

    • setNoWaitAfter boolean (optional)#

      :::警告[已弃用] 这个选项没有效果。 :::

      此选项无效。

    • setPosition Position (optional)#

      相对于元素内边距盒左上角使用的一个点。如果未指定,则使用元素的某个可见点。

    • setTimeout double (optional)#

      最长时间(以毫秒为单位)。默认值为 30000(30 秒)。传入 0 可禁用超时。默认值可以通过使用 BrowserContext.setDefaultTimeout()Page.setDefaultTimeout() 方法进行更改。

    • setTrial boolean (optional)#

      设置后,该方法仅执行 可操作性 检查,而跳过实际操作。默认为 false。在不执行操作的情况下,等待元素准备好进行操作时非常有用。

返回


setInputFiles

Added before v1.9 elementHandle.setInputFiles
Discouraged

请改用基于定位器的 Locator.setInputFiles()。了解更多关于 定位器 的信息。

🌐 Use locator-based Locator.setInputFiles() instead. Read more about locators.

将文件输入的值设置为这些文件路径或文件。如果某些 filePaths 是相对路径,则相对于当前工作目录进行解析。对于空数组,会清除选中的文件。对于带有 [webkitdirectory] 属性的输入,只支持单个目录路径。

🌐 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. For inputs with a [webkitdirectory] attribute, only a single directory path is supported.

此方法期望 ElementHandle 指向一个 输入元素。但是,如果该元素位于具有关联 控件<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.

用法

ElementHandle.setInputFiles(files);
ElementHandle.setInputFiles(files, options);

参数

  • files Path | Path[] | FilePayload | FilePayload[]#

  • options ElementHandle.SetInputFilesOptions (optional)

返回


tap

Added before v1.9 elementHandle.tap
Discouraged

请改为使用基于定位器的 Locator.tap()。了解更多关于 定位器 的信息。

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

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

🌐 This method taps the element by performing the following steps:

  1. 等待元素的 actionability 检查,除非设置了 setForce 选项。
  2. 如果需要,将元素滚动到视图中。
  3. 使用 Page.touchscreen() 点击元素的中心,或指定的 setPosition 位置。

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

🌐 If the element is detached from the DOM at any moment during the action, this method throws.

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

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

note

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

用法

ElementHandle.tap();
ElementHandle.tap(options);

参数

  • options ElementHandle.TapOptions (optional)
    • setForce boolean (optional)#

      是否绕过 可操作性 检查。默认值为 false

    • setModifiers List<enum KeyboardModifier { ALT, CONTROL, CONTROLORMETA, META, SHIFT }> (optional)#

      要按下的修饰键。确保在操作过程中仅按下这些修饰键,然后恢复当前的修饰键。如果未指定,则使用当前按下的修饰键。“ControlOrMeta”在 Windows 和 Linux 上对应“Control”,在 macOS 上对应“Meta”。

    • setNoWaitAfter boolean (optional)#

      :::警告[已弃用] 这个选项没有效果。

此选项无效。

  • setPosition Position (optional)#

    相对于元素内边距盒左上角使用的一个点。如果未指定,则使用元素的某个可见点。

  • setTimeout double (optional)#

    最长时间(以毫秒为单位)。默认值为 30000(30 秒)。传入 0 可禁用超时。默认值可以通过使用 BrowserContext.setDefaultTimeout()Page.setDefaultTimeout() 方法进行更改。

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

    设置后,该方法仅执行 可操作性 检查,而跳过实际操作。默认为 false。在不执行操作的情况下,等待元素准备好进行操作时非常有用。

返回


textContent

Added before v1.9 elementHandle.textContent
Discouraged

请改为使用基于定位器的 Locator.textContent()。阅读更多关于 定位器 的内容。

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

返回 node.textContent

🌐 Returns the node.textContent.

用法

ElementHandle.textContent();

返回


type

Added before v1.9 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().

用法

参数

  • text String#

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

  • options ElementHandle.TypeOptions (optional)

    • setDelay double (optional)#

      按键之间的等待时间,以毫秒为单位。默认为 0。

    • setNoWaitAfter boolean (optional)#

      :::警告[已弃用] 这个选项没有效果。 :::

      此选项无效。

    • setTimeout double (optional)#

      最长时间(以毫秒为单位)。默认值为 30000(30 秒)。传入 0 可禁用超时。默认值可以通过使用 BrowserContext.setDefaultTimeout()Page.setDefaultTimeout() 方法进行更改。

返回


uncheck

Added before v1.9 elementHandle.uncheck
Discouraged

请改为使用基于定位器的 Locator.uncheck()。阅读更多关于 定位器 的信息。

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

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

🌐 This method checks the element by performing the following steps:

  1. 确保该元素是复选框或单选按钮输入。如果不是,该方法会抛出异常。如果元素已经未选中,该方法会立即返回。
  2. 等待元素的 actionability 检查,除非设置了 setForce 选项。
  3. 如果需要,将元素滚动到视图中。
  4. 使用 Page.mouse() 在元素中心点击。
  5. 确保该元素现在未被选中。如果不是,这种方法会抛出异常。

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

🌐 If the element is detached from the DOM at any moment during the action, this method throws.

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

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

用法

ElementHandle.uncheck();
ElementHandle.uncheck(options);

参数

  • options ElementHandle.UncheckOptions (optional)
    • setForce boolean (optional)#

      是否绕过 可操作性 检查。默认值为 false

    • setNoWaitAfter boolean (optional)#

      :::警告[已弃用] 这个选项没有效果。 :::

      此选项无效。

    • setPosition Position (optional) Added in: v1.11#

      相对于元素内边距盒左上角使用的一个点。如果未指定,则使用元素的某个可见点。

    • setTimeout double (optional)#

      最长时间(以毫秒为单位)。默认值为 30000(30 秒)。传入 0 可禁用超时。默认值可以通过使用 BrowserContext.setDefaultTimeout()Page.setDefaultTimeout() 方法进行更改。

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

      设置后,该方法仅执行 可操作性 检查,而跳过实际操作。默认为 false。在不执行操作的情况下,等待元素准备好进行操作时非常有用。

返回


waitForSelector

Added before v1.9 elementHandle.waitForSelector
Discouraged

使用用于声明可见性的网页断言,或基于定位器的[Locator.waitFor()](/api/class-locator.mdx#locator-wait-for)。

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

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

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

等待与元素句柄相关的 selector 满足 setState 选项(要么从 DOM 中出现/消失,要么变得可见/隐藏)。如果在调用该方法时 selector 已经满足条件,该方法将立即返回。如果在 setTimeout 毫秒内选择器仍未满足条件,该函数将抛出异常。

🌐 Wait for the selector relative to the element handle to satisfy setState 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 setTimeout milliseconds, the function will throw.

用法

page.setContent("<div><span></span></div>");
ElementHandle div = page.querySelector("div");
// Waiting for the "span" selector relative to the div.
ElementHandle span = div.waitForSelector("span", new ElementHandle.WaitForSelectorOptions()
.setState(WaitForSelectorState.ATTACHED));
note

此方法在页面导航间不起作用,请改用 Page.waitForSelector()

参数

  • selector String#

    要查询的选择器。

  • options ElementHandle.WaitForSelectorOptions (optional)

    • setState enum WaitForSelectorState { ATTACHED, DETACHED, VISIBLE, HIDDEN } (optional)#

      默认值为 'visible'。可以是以下之一:

      • 'attached' - 等待元素出现在 DOM 中。
      • 'detached' - 等待元素不再出现在 DOM 中。
      • 'visible' - 等待元素有非空的边界框并且不含 visibility:hidden。请注意,没有任何内容或含有 display:none 的元素会有空的边界框,并且不被认为是可见的。
      • 'hidden' - 等待元素被从 DOM 中移除,或其边界框为空,或为 visibility:hidden。这与 'visible' 选项相反。
    • setStrict boolean (optional) Added in: v1.15#

      当值为 true 时,该调用要求选择器解析为单个元素。如果给定的选择器解析为多个元素,该调用将抛出异常。

    • setTimeout double (optional)#

      最长时间(以毫秒为单位)。默认值为 30000(30 秒)。传入 0 可禁用超时。默认值可以通过使用 BrowserContext.setDefaultTimeout()Page.setDefaultTimeout() 方法进行更改。

返回