Skip to main content
Version: 24.38.0

ElementHandle 类

🌐 ElementHandle class

ElementHandle 表示页内 DOM 元素。

🌐 ElementHandle represents an in-page DOM element.

语法

🌐 Signature

export declare abstract class ElementHandle<ElementType extends Node = Element> extends JSHandle<ElementType>

Extends: JSHandle<ElementType>

附注

🌐 Remarks

可以使用 Page.$() 方法创建 ElementHandles。

🌐 ElementHandles can be created with the Page.$() method.

import puppeteer from 'puppeteer';

const browser = await puppeteer.launch();
const page = await browser.newPage();
await page.goto('https://example.com');
const hrefElement = await page.$('a');
await hrefElement.click();
// ...

ElementHandle 会防止 DOM 元素被垃圾回收,除非该句柄被释放。当其关联的框架被导航到其他页面或父上下文被销毁时,ElementHandle 会自动被释放。

🌐 ElementHandle prevents the DOM element from being garbage-collected unless the handle is disposed. ElementHandles are auto-disposed when their associated frame is navigated away or the parent context gets destroyed.

ElementHandle 实例可以作为 Page.$eval()Page.evaluate() 方法的参数使用。

🌐 ElementHandle instances can be used as arguments in Page.$eval() and Page.evaluate() methods.

如果你使用 TypeScript,ElementHandle 需要一个泛型参数,用来表示句柄所持有的元素类型。例如,如果你有一个指向 <select> 元素的句柄,你可以将其类型标注为 ElementHandle<HTMLSelectElement>,这样你就可以获得更好的类型检查。

🌐 If you're using TypeScript, ElementHandle takes a generic argument that denotes the type of element the handle is holding within. For example, if you have a handle to a <select> element, you can type it as ElementHandle<HTMLSelectElement> and you get some nicer type checks.

这个类的构造函数被标记为内部。第三方代码不应直接调用构造函数或创建继承 ElementHandle 类的子类。

🌐 The constructor for this class is marked as internal. Third-party code should not call the constructor directly or create subclasses that extend the ElementHandle class.

属性

🌐 Properties

属性

🌐 Property

修饰符

🌐 Modifiers

类型

🌐 Type

描述

🌐 Description

frame

readonly

框架

与当前句柄对应的帧。

🌐 Frame corresponding to the current handle.

方法

🌐 Methods

方法

🌐 Method

修饰符

🌐 Modifiers

描述

🌐 Description

$(selector)

查询当前元素以查找与给定选择器匹配的元素。

🌐 Queries the current element for an element matching the given selector.

$$(selector, options)

查询当前元素中与给定选择器匹配的所有元素。

🌐 Queries the current element for all elements matching the given selector.

$$eval(selector, pageFunction, args)

对当前元素中与给定选择器匹配的元素数组运行给定函数。

🌐 Runs the given function on an array of elements matching the given selector in the current element.

如果给定的函数返回一个 Promise,那么此方法将等待直到 Promise 解析。

🌐 If the given function returns a promise, then this method will wait till the promise resolves.

$eval(selector, pageFunction, args)

在当前元素中与给定选择器匹配的第一个元素上运行给定函数。

🌐 Runs the given function on the first element matching the given selector in the current element.

如果给定的函数返回一个 Promise,那么此方法将等待直到 Promise 解析。

🌐 If the given function returns a promise, then this method will wait till the promise resolves.

asLocator(this)

基于 ElementHandle 创建一个定位器。这不会允许在元素句柄过期时刷新它,但允许重用其他定位器的前置条件。

🌐 Creates a locator based on an ElementHandle. This would not allow refreshing the element handle if it is stale but it allows re-using other locator pre-conditions.

autofill(data)

如果该元素是表单输入项,你可以使用 ElementHandle.autofill() 来测试表单是否与浏览器的自动填充功能兼容。如果表单无法自动填充,则会抛出错误。

🌐 If the element is a form input, you can use ElementHandle.autofill() to test if the form is compatible with the browser's autofill implementation. Throws an error if the form cannot be autofilled.

附注

目前,Puppeteer 仅支持自动填充信用卡信息,并且在 Chrome 中仅支持新的 headless 和 headful 模式。

🌐 Currently, Puppeteer supports auto-filling credit card information only and in Chrome in the new headless and headful modes only.

// Select an input on the credit card form.
const name = await page.waitForSelector('form #name');
// Trigger autofill with the desired data.
await name.autofill({
creditCard: {
number: '4444444444444444',
name: 'John Smith',
expiryMonth: '01',
expiryYear: '2030',
cvc: '123',
},
});
backendNodeId()

使用 Chrome DevTools 协议连接时,它会返回元素的 DOM.BackendNodeId。

🌐 When connected using Chrome DevTools Protocol, it returns a DOM.BackendNodeId for the element.

boundingBox()

此方法返回元素的边界框(相对于主框架),如果元素不属于布局,则返回 null(示例:display: none)。

🌐 This method returns the bounding box of the element (relative to the main frame), or null if the element is not part of the layout (example: display: none).

boxModel()

此方法返回元素的框,或者如果元素不属于布局,则返回 null(示例:display: none)。

🌐 This method returns boxes of the element, or null if the element is not part of the layout (example: display: none).

附注

盒子表示为一个点数组;每个点是一个对象 {x, y}。盒子的点按顺时针排序。

🌐 Boxes are represented as an array of points; Each Point is an object {x, y}. Box points are sorted clock-wise.

click(this, options)

此方法在需要时将元素滚动到可见区域,然后使用 Page.mouse 点击元素的中心。如果元素已从 DOM 中分离,该方法将抛出错误。

🌐 This method scrolls element into view if needed, and then uses Page.mouse to click in the center of the element. If the element is detached from DOM, the method throws an error.

clickablePoint(offset)

返回元素内的中点,除非提供了特定的偏移量。

🌐 Returns the middle point within an element unless a specific offset is provided.

contentFrame(this)

解析与该元素关联的框架(如果有)。对于 HTMLIFrameElements 始终存在。

🌐 Resolves the frame associated with the element, if any. Always exists for HTMLIFrameElements.

contentFrame()
drag(this, target)

将元素拖动到给定元素或点上。

🌐 Drags an element over the given element or point.

dragAndDrop(this, target, options)

deprecated

已弃用:

请改用 ElementHandle.drop

🌐 Use ElementHandle.drop instead.

dragEnter(this, data)

deprecated

已弃用:

请勿使用。拖动时将自动执行 dragenter

🌐 Do not use. dragenter will automatically be performed during dragging.

dragOver(this, data)

deprecated

已弃用:

不要使用。dragover 将在拖动时自动执行。

🌐 Do not use. dragover will automatically be performed during dragging.

drop(this, element)

将给定元素放到当前元素上。

🌐 Drops the given element onto the current one.

drop(this, data)

deprecated

已弃用:

不再支持。

🌐 No longer supported.

focus()

在该元素上调用 focus

🌐 Calls focus on the element.

hover(this)

此方法在需要时将元素滚动到视图中,然后使用 Page.mouse 将鼠标悬停在元素的中心。如果元素已从 DOM 中分离,该方法将抛出错误。

🌐 This method scrolls element into view if needed, and then uses Page.mouse to hover over the center of the element. If the element is detached from DOM, the method throws an error.

isHidden()

如果以下至少一项为真,则认为元素是隐藏的:

🌐 An element is considered to be hidden if at least one of the following is true:

isIntersectingViewport(this, options)

如果元素在当前视口中可见,则解析为 true。如果元素是 SVG,我们会改为检查 SVG 所属的元素是否在视口中。参见 https://crbug.com/963246。

🌐 Resolves to true if the element is visible in the current viewport. If an element is an SVG, we check if the svg owner element is in the viewport instead. See https://crbug.com/963246.

isVisible()

如果以下所有条件都为真,则认为元素是可见的:

🌐 An element is considered to be visible if all of the following is true:

press(key, options)

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

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

附注

如果 key 是单个字符,并且除了 Shift 之外没有按下任何修饰键,也会生成 keypress/input 事件。可以指定 text 选项以强制生成输入事件。

🌐 If key is a single character and no modifier keys besides Shift are being held down, a keypress/input event will also be generated. The text option can be specified to force an input event to be generated.

注意 修饰键会影响 elementHandle.press。按住 Shift 会以大写输入文本。

screenshot(options)

如果需要,此方法会将元素滚动到可视区域,然后使用 Page.screenshot() 对元素进行截图。如果元素已从 DOM 中分离,该方法会抛出错误。

🌐 This method scrolls element into view if needed, and then uses Page.screenshot() to take a screenshot of the element. If the element is detached from DOM, the method throws an error.

screenshot(options)
scrollIntoView(this)

使用自动化协议客户端或通过调用 element.scrollIntoView 将元素滚动到视图中。

🌐 Scrolls the element into view using either the automation protocol client or by calling element.scrollIntoView.

select(values)

一旦所有提供的选项都被选择,会触发 changeinput 事件。如果没有匹配 selector<select> 元素,该方法将抛出错误。

🌐 Triggers a change and input event once all the provided options have been selected. If there's no <select> element matching selector, the method throws an error.

tap(this)

此方法在需要时将元素滚动到视图中,然后使用 Touchscreen.tap() 点击元素的中心。如果元素已从 DOM 中分离,该方法会抛出错误。

🌐 This method scrolls element into view if needed, and then uses Touchscreen.tap() to tap in the center of the element. If the element is detached from DOM, the method throws an error.

toElement(tagName)

将当前句柄转换为给定的元素类型。

🌐 Converts the current handle to the given element type.

touchEnd(this)
touchMove(this, touch)

此方法在需要时将元素滚动到视图中,然后将触摸移动到元素的中心。

🌐 This method scrolls the element into view if needed, and then moves the touch to the center of the element.

touchStart(this)

此方法在需要时将元素滚动到视图中,然后在元素的中心启动触摸。

🌐 This method scrolls the element into view if needed, and then starts a touch in the center of the element.

type(text, options)

聚焦元素,然后为文本中的每个字符发送一个 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().

uploadFile(this, paths)

input 元素的值设置为给定的文件路径。

🌐 Sets the value of an input element to the given file paths.

附注

这不会验证文件路径是否存在。此外,如果路径是相对的,则它是相对于当前工作目录解析的。对于连接到远程 Chrome 环境的本地脚本,路径必须是绝对路径。

🌐 This will not validate whether the file paths exists. Also, if a path is relative, then it is resolved against the current working directory. For locals script connecting to remote chrome environments, paths must be absolute.

waitForSelector(selector, options)

等待与给定选择器匹配的元素出现在当前元素中。

🌐 Wait for an element matching the given selector to appear in the current element.

Frame.waitForSelector() 不同,此方法在页面导航期间或元素从 DOM 中被移除时不起作用。

🌐 Unlike Frame.waitForSelector(), this method does not work across navigations or if the element is detached from DOM.