Skip to main content
Version: 23.2.0

ElementHandle.$$eval() 方法

¥ElementHandle.$$eval() method

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

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

签名

¥Signature

class ElementHandle {
$$eval<
Selector extends string,
Params extends unknown[],
Func extends EvaluateFuncWith<
Array<NodeFor<Selector>>,
Params
> = EvaluateFuncWith<Array<NodeFor<Selector>>, Params>,
>(
selector: Selector,
pageFunction: Func | string,
...args: Params
): Promise<Awaited<ReturnType<Func>>>;
}

参数

¥Parameters

范围

类型

描述

selector

选择器

要查询页面的 selectorCSS 选择器 可以按原样传递,Puppeteer 特定的选择器语法 允许通过 texta11y 角色和名称xpath跨影子根组合这些查询 进行查询。或者,你可以使用 prefix 指定选择器类型。

pageFunction

功能 | 字符串

要在元素页面上下文中评估的函数。与给定选择器匹配的元素数组将作为其第一个参数传递给函数。

args

参数

要传递给 pageFunction 的其他参数。

Returns:

Promise<Awaited<ReturnType<Func>>>

对函数结果的 promise。

¥A promise to the result of the function.

示例

¥Example

HTML:

<div class="feed">
<div class="tweet">Hello!</div>
<div class="tweet">Hi!</div>
</div>

JavaScript:

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