Skip to main content

ElementHandle

ElementHandle 表示页面内的 DOM 元素。可以通过 Page.QuerySelectorAsync() 方法创建 ElementHandle。

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

Discouraged

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

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

var handle = await page.QuerySelectorAsync("a");
await handle.ClickAsync();

ElementHandle 会阻止 DOM 元素被垃圾回收,除非通过 JsHandle.DisposeAsync() 释放该句柄。当其所属的框架被导航时,ElementHandles 会自动释放。

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

ElementHandle 实例可以作为 Page.EvalOnSelectorAsync()Page.EvaluateAsync() 方法的参数使用。

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

var handle = await page.QuerySelectorAsync("text=Submit");
await handle.HoverAsync();
await handle.ClickAsync();

使用定位器时,每次使用 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.

var locator = page.GetByText("Submit");
await locator.HoverAsync();
await locator.ClickAsync();

方法

🌐 Methods

BoundingBoxAsync

Added before v1.9 elementHandle.BoundingBoxAsync

此方法返回元素的边界框,如果元素不可见,则返回 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.

用法

var box = await elementHandle.BoundingBoxAsync();
await page.Mouse.ClickAsync(box.X + box.Width / 2, box.Y + box.Height / 2);

返回

  • 边界框?#
    • x [float]

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

    • y [float]

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

    • width [float]

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

    • height [float]

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


ContentFrameAsync

Added before v1.9 elementHandle.ContentFrameAsync

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

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

用法

await ElementHandle.ContentFrameAsync();

返回


OwnerFrameAsync

Added before v1.9 elementHandle.OwnerFrameAsync

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

🌐 Returns the frame containing the given element.

用法

await ElementHandle.OwnerFrameAsync();

返回


WaitForElementStateAsync

Added before v1.9 elementHandle.WaitForElementStateAsync

当元素满足状态时返回。

🌐 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" 等待元素可编辑

如果该元素在 Timeout 毫秒内未满足条件,此方法将抛出异常。

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

用法

await ElementHandle.WaitForElementStateAsync(state, options);

参数

  • state enum ElementState { Visible, Hidden, Stable, Enabled, Disabled, Editable }#

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

  • options ElementHandleWaitForElementStateOptions? (optional)

返回


已弃用

🌐 Deprecated

CheckAsync

Added before v1.9 elementHandle.CheckAsync
Discouraged

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

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

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

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

  1. 确保该元素是复选框或单选按钮输入。如果不是,该方法会抛出异常。如果元素已经被选中,该方法会立即返回。
  2. 等待对该元素的可操作性检查,除非设置了强制选项。
  3. 如果需要,将元素滚动到视图中。
  4. 使用 Page.Mouse 点击元素的中心。
  5. 确保该元素现在已被选中。如果没有,该方法会抛出异常。

如果该元素在操作过程中的任何时刻与 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.

用法

await ElementHandle.CheckAsync(options);

参数

  • options ElementHandleCheckOptions? (optional)
    • Force bool? (optional)#

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

    • NoWaitAfter bool? (optional)#

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

      此选项无效。

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

      • X [float]

      • Y [float]

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

    • Timeout [float]? (optional)#

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

    • Trial bool? (optional) Added in: v1.11#

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

返回


ClickAsync

Added before v1.9 elementHandle.ClickAsync
Discouraged

请使用基于定位器的[Locator.ClickAsync()](/api/class-locator.mdx#locator-click)。阅读更多关于[定位器](../locators.mdx)的信息。

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

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

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

  1. 等待对该元素的可操作性检查,除非设置了强制选项。
  2. 如果需要,将元素滚动到视图中。
  3. 使用 Page.Mouse 点击元素中心,或指定的 Position 位置。
  4. 等待已启动的导航要么成功,要么失败,除非设置了 NoWaitAfter 选项。

如果该元素在操作过程中的任何时刻与 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.

用法

await ElementHandle.ClickAsync(options);

参数

  • options ElementHandleClickOptions? (optional)
    • Button enum MouseButton { Left, Right, Middle }? (optional)#

      默认为 left

    • ClickCount int? (optional)#

      默认为 1。请参阅 UIEvent.detail

    • Delay [float]? (optional)#

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

    • Force bool? (optional)#

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

    • Modifiers IEnumerable?<enum KeyboardModifier { Alt, Control, ControlOrMeta, Meta, Shift }> (optional)#

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

    • NoWaitAfter bool? (optional)#

      已弃用

      该选项将来默认值为 true

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

    • Position Position? (optional)#

      • X [float]

      • Y [float]

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

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

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

    • Timeout [float]? (optional)#

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

    • Trial bool? (optional) Added in: v1.11#

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

返回


DblClickAsync

Added before v1.9 elementHandle.DblClickAsync
Discouraged

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

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

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

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

  1. 等待对该元素的可操作性检查,除非设置了强制选项。
  2. 如果需要,将元素滚动到视图中。
  3. 使用 Page.Mouse 在元素中心或指定的 Position 双击。

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

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

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

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

note

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

用法

await ElementHandle.DblClickAsync(options);

参数

  • options ElementHandleDblClickOptions? (optional)
    • Button enum MouseButton { Left, Right, Middle }? (optional)#

      默认为 left

    • Delay [float]? (optional)#

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

    • Force bool? (optional)#

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

    • Modifiers IEnumerable?<enum KeyboardModifier { Alt, Control, ControlOrMeta, Meta, Shift }> (optional)#

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

    • NoWaitAfter bool? (optional)#

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

此选项无效。

  • Position Position? (optional)#

    • X [float]

    • Y [float]

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

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

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

  • Timeout [float]? (optional)#

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

  • Trial bool? (optional) Added in: v1.11#

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

返回


DispatchEventAsync

Added before v1.9 elementHandle.DispatchEventAsync
Discouraged

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

🌐 Use locator-based Locator.DispatchEventAsync() 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().

用法

await elementHandle.DispatchEventAsync("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:

var dataTransfer = await page.EvaluateHandleAsync("() => new DataTransfer()");
await elementHandle.DispatchEventAsync("dragstart", new Dictionary<string, object>
{
{ "dataTransfer", dataTransfer }
});

参数

  • type string#

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

  • eventInit EvaluationArgument? (optional)#

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

返回


EvalOnSelectorAsync

Added in: v1.9 elementHandle.EvalOnSelectorAsync
Discouraged

此方法不会等待元素通过可操作性检查,因此可能导致测试不稳定。请改用 Locator.EvaluateAsync()、其他 Locator 辅助方法或以网页为主的断言。

🌐 This method does not wait for the element to pass actionability checks and therefore can lead to the flaky tests. Use Locator.EvaluateAsync(), 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.EvalOnSelectorAsync() 会等待该 promise 解析并返回其值。

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

用法

var tweetHandle = await page.QuerySelectorAsync(".tweet");
Assert.AreEqual("100", await tweetHandle.EvalOnSelectorAsync(".like", "node => node.innerText"));
Assert.AreEqual("10", await tweetHandle.EvalOnSelectorAsync(".retweets", "node => node.innerText"));

参数

  • selector string#

    要查询的选择器。

  • expression string#

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

  • arg EvaluationArgument? (optional)#

    可选参数,传递给 expression

返回

  • [object]#

EvalOnSelectorAllAsync

Added in: v1.9 elementHandle.EvalOnSelectorAllAsync
Discouraged

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

🌐 In most cases, Locator.EvaluateAllAsync(), 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.EvalOnSelectorAllAsync() 会等待该 promise 解决并返回其值。

🌐 If expression returns a Promise, then ElementHandle.EvalOnSelectorAllAsync() 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>
var feedHandle = await page.QuerySelectorAsync(".feed");
Assert.AreEqual(new [] { "Hello!", "Hi!" }, await feedHandle.EvalOnSelectorAllAsync<string[]>(".tweet", "nodes => nodes.map(n => n.innerText)"));

参数

  • selector string#

    要查询的选择器。

  • expression string#

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

  • arg EvaluationArgument? (optional)#

    可选参数,传递给 expression

返回

  • [object]#

FillAsync

Added before v1.9 elementHandle.FillAsync
Discouraged

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

🌐 Use locator-based Locator.FillAsync() 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.PressSequentiallyAsync()

🌐 To send fine-grained keyboard events, use Locator.PressSequentiallyAsync().

用法

await ElementHandle.FillAsync(value, options);

参数

  • value string#

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

  • options ElementHandleFillOptions? (optional)

    • Force bool? (optional) Added in: v1.13#

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

    • NoWaitAfter bool? (optional)#

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

      此选项无效。

    • Timeout [float]? (optional)#

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

返回


FocusAsync

Added before v1.9 elementHandle.FocusAsync
Discouraged

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

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

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

🌐 Calls focus on the element.

用法

await ElementHandle.FocusAsync();

返回


GetAttributeAsync

Added before v1.9 elementHandle.GetAttributeAsync
Discouraged

请使用基于定位器的 [Locator.GetAttributeAsync()](/api/class-locator.mdx#locator-get-attribute)。阅读更多关于[定位器](../locators.mdx)的信息。

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

返回元素属性值。

🌐 Returns element attribute value.

用法

await ElementHandle.GetAttributeAsync(name);

参数

  • name string#

    要获取其值的属性名称。

返回


HoverAsync

Added before v1.9 elementHandle.HoverAsync
Discouraged

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

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

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

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

  1. 等待对该元素的可操作性检查,除非设置了强制选项。
  2. 如果需要,将元素滚动到视图中。
  3. 使用 Page.Mouse 将鼠标悬停在元素的中心,或指定的 Position 位置。

如果该元素在操作过程中的任何时刻与 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.

用法

await ElementHandle.HoverAsync(options);

参数

  • options ElementHandleHoverOptions? (optional)
    • Force bool? (optional)#

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

    • Modifiers IEnumerable?<enum KeyboardModifier { Alt, Control, ControlOrMeta, Meta, Shift }> (optional)#

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

    • NoWaitAfter bool? (optional) Added in: v1.28#

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

      此选项无效。

    • Position Position? (optional)#

      • X [float]

      • Y [float]

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

    • Timeout [float]? (optional)#

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

    • Trial bool? (optional) Added in: v1.11#

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

返回


InnerHTMLAsync

Added before v1.9 elementHandle.InnerHTMLAsync
Discouraged

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

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

返回 element.innerHTML

🌐 Returns the element.innerHTML.

用法

await ElementHandle.InnerHTMLAsync();

返回


InnerTextAsync

Added before v1.9 elementHandle.InnerTextAsync
Discouraged

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

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

返回 element.innerText

🌐 Returns the element.innerText.

用法

await ElementHandle.InnerTextAsync();

返回


InputValueAsync

Added in: v1.13 elementHandle.InputValueAsync
Discouraged

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

🌐 Use locator-based Locator.InputValueAsync() 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.

用法

await ElementHandle.InputValueAsync(options);

参数

返回


IsCheckedAsync

Added before v1.9 elementHandle.IsCheckedAsync
Discouraged

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

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

返回元素是否被选中。如果元素不是复选框或单选按钮,将抛出异常。

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

用法

await ElementHandle.IsCheckedAsync();

返回


IsDisabledAsync

Added before v1.9 elementHandle.IsDisabledAsync
Discouraged

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

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

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

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

用法

await ElementHandle.IsDisabledAsync();

返回


IsEditableAsync

Added before v1.9 elementHandle.IsEditableAsync
Discouraged

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

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

返回元素是否可编辑

🌐 Returns whether the element is editable.

用法

await ElementHandle.IsEditableAsync();

返回


IsEnabledAsync

Added before v1.9 elementHandle.IsEnabledAsync
Discouraged

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

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

返回元素是否已启用

🌐 Returns whether the element is enabled.

用法

await ElementHandle.IsEnabledAsync();

返回


IsHiddenAsync

Added before v1.9 elementHandle.IsHiddenAsync
Discouraged

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

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

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

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

用法

await ElementHandle.IsHiddenAsync();

返回


IsVisibleAsync

Added before v1.9 elementHandle.IsVisibleAsync
Discouraged

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

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

返回元素是否可见

🌐 Returns whether the element is visible.

用法

await ElementHandle.IsVisibleAsync();

返回


PressAsync

Added before v1.9 elementHandle.PressAsync
Discouraged

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

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

聚焦该元素,然后使用 Keyboard.DownAsync()Keyboard.UpAsync()

🌐 Focuses the element, and then uses Keyboard.DownAsync() and Keyboard.UpAsync().

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.

用法

await ElementHandle.PressAsync(key, options);

参数

  • key string#

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

  • options ElementHandlePressOptions? (optional)

    • Delay [float]? (optional)#

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

    • NoWaitAfter bool? (optional)#

      已弃用

      该选项将来默认值为 true

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

    • Timeout [float]? (optional)#

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

返回


QuerySelectorAsync

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

用法

await ElementHandle.QuerySelectorAsync(selector);

参数

  • selector string#

    要查询的选择器。

返回


QuerySelectorAllAsync

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

用法

await ElementHandle.QuerySelectorAllAsync(selector);

参数

  • selector string#

    要查询的选择器。

返回


ScreenshotAsync

Added before v1.9 elementHandle.ScreenshotAsync
Discouraged

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

🌐 Use locator-based Locator.ScreenshotAsync() 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.

用法

await ElementHandle.ScreenshotAsync(options);

参数

  • options ElementHandleScreenshotOptions? (optional)
    • Animations enum ScreenshotAnimations { Disabled, Allow }? (optional)#

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

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

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

    • Caret enum ScreenshotCaret { Hide, Initial }? (optional)#

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

    • Mask IEnumerable?<Locator> (optional)#

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

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

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

    • OmitBackground bool? (optional)#

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

    • Path string? (optional)#

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

    • Quality int? (optional)#

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

    • Scale enum ScreenshotScale { Css, Device }? (optional)#

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

      默认为 "device"

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

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

    • Timeout [float]? (optional)#

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

    • Type enum ScreenshotType { Png, Jpeg }? (optional)#

      指定截图类型,默认为 png

返回


ScrollIntoViewIfNeededAsync

Added before v1.9 elementHandle.ScrollIntoViewIfNeededAsync
Discouraged

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

🌐 Use locator-based Locator.ScrollIntoViewIfNeededAsync() 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.

用法

await ElementHandle.ScrollIntoViewIfNeededAsync(options);

参数

  • options ElementHandleScrollIntoViewIfNeededOptions? (optional)

返回


SelectOptionAsync

Added before v1.9 elementHandle.SelectOptionAsync
Discouraged

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

🌐 Use locator-based Locator.SelectOptionAsync() 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
await handle.SelectOptionAsync(new[] { "blue" });
// single selection matching the label
await handle.SelectOptionAsync(new[] { new SelectOptionValue() { Label = "blue" } });
// multiple selection
await handle.SelectOptionAsync(new[] { "red", "green", "blue" });
// multiple selection for blue, red and second option
await handle.SelectOptionAsync(new[] {
new SelectOptionValue() { Label = "blue" },
new SelectOptionValue() { Index = 2 },
new SelectOptionValue() { Value = "red" }});

参数

  • values string | ElementHandle | IEnumerable | SelectOption | IEnumerable | IEnumerable?#

    • Value string? (optional)

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

    • Label string? (optional)

      option.label 匹配。可选。

    • Index int? (optional)

      按索引匹配。可选。

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

  • options ElementHandleSelectOptionOptions? (optional)

    • Force bool? (optional) Added in: v1.13#

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

    • NoWaitAfter bool? (optional)#

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

      此选项无效。

    • Timeout [float]? (optional)#

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

返回


SelectTextAsync

Added before v1.9 elementHandle.SelectTextAsync
Discouraged

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

🌐 Use locator-based Locator.SelectTextAsync() 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.

用法

await ElementHandle.SelectTextAsync(options);

参数

  • options ElementHandleSelectTextOptions? (optional)

返回


SetCheckedAsync

Added in: v1.15 elementHandle.SetCheckedAsync
Discouraged

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

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

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

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

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

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

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

用法

await ElementHandle.SetCheckedAsync(checked, options);

参数

  • checkedState bool#

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

  • options ElementHandleSetCheckedOptions? (optional)

    • Force bool? (optional)#

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

    • NoWaitAfter bool? (optional)#

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

      此选项无效。

    • Position Position? (optional)#

      • X [float]

      • Y [float]

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

    • Timeout [float]? (optional)#

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

    • Trial bool? (optional)#

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

返回


SetInputFilesAsync

Added before v1.9 elementHandle.SetInputFilesAsync
Discouraged

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

🌐 Use locator-based Locator.SetInputFilesAsync() 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.

用法

await ElementHandle.SetInputFilesAsync(files, options);

参数

返回


TapAsync

Added before v1.9 elementHandle.TapAsync
Discouraged

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

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

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

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

  1. 等待对该元素的可操作性检查,除非设置了强制选项。
  2. 如果需要,将元素滚动到视图中。
  3. 使用 Page.Touchscreen 点击元素的中心,或指定的 Position

如果该元素在操作过程中的任何时刻与 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.

note

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

用法

await ElementHandle.TapAsync(options);

参数

  • options ElementHandleTapOptions? (optional)
    • Force bool? (optional)#

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

    • Modifiers IEnumerable?<enum KeyboardModifier { Alt, Control, ControlOrMeta, Meta, Shift }> (optional)#

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

    • NoWaitAfter bool? (optional)#

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

此选项无效。

  • Position Position? (optional)#

    • X [float]

    • Y [float]

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

  • Timeout [float]? (optional)#

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

  • Trial bool? (optional) Added in: v1.11#

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

返回


TextContentAsync

Added before v1.9 elementHandle.TextContentAsync
Discouraged

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

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

返回 node.textContent

🌐 Returns the node.textContent.

用法

await ElementHandle.TextContentAsync();

返回


TypeAsync

Added before v1.9 elementHandle.TypeAsync
已弃用

在大多数情况下,你应该使用 Locator.FillAsync()。只有在页面上需要特殊的键盘处理时,才需要逐个按键——在这种情况下使用 Locator.PressSequentiallyAsync()

🌐 In most cases, you should use Locator.FillAsync() instead. You only need to press keys one by one if there is special keyboard handling on the page - in this case use Locator.PressSequentiallyAsync().

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

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

要按下特殊键,如 ControlArrowDown,请使用 ElementHandle.PressAsync()

🌐 To press a special key, like Control or ArrowDown, use ElementHandle.PressAsync().

用法

参数

  • text string#

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

  • options ElementHandleTypeOptions? (optional)

    • Delay [float]? (optional)#

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

    • NoWaitAfter bool? (optional)#

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

      此选项无效。

    • Timeout [float]? (optional)#

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

返回


UncheckAsync

Added before v1.9 elementHandle.UncheckAsync
Discouraged

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

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

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

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

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

如果该元素在操作过程中的任何时刻与 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.

用法

await ElementHandle.UncheckAsync(options);

参数

  • options ElementHandleUncheckOptions? (optional)
    • Force bool? (optional)#

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

    • NoWaitAfter bool? (optional)#

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

      此选项无效。

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

      • X [float]

      • Y [float]

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

    • Timeout [float]? (optional)#

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

    • Trial bool? (optional) Added in: v1.11#

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

返回


WaitForSelectorAsync

Added before v1.9 elementHandle.WaitForSelectorAsync
Discouraged

而是使用断言元素可见的网页断言或基于定位器的 Locator.WaitForAsync()

🌐 Use web assertions that assert visibility or a locator-based Locator.WaitForAsync() 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.

用法

await page.SetContentAsync("<div><span></span></div>");
var div = await page.QuerySelectorAsync("div");
// Waiting for the "span" selector relative to the div.
var span = await page.WaitForSelectorAsync("span", WaitForSelectorState.Attached);
note

此方法在跨页面导航时无效,请改用 Page.WaitForSelectorAsync()

参数

  • selector string#

    要查询的选择器。

  • options ElementHandleWaitForSelectorOptions? (optional)

    • State enum WaitForSelectorState { Attached, Detached, Visible, Hidden }? (optional)#

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

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

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

    • Timeout [float]? (optional)#

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

返回