Skip to main content
Version: 23.2.0

Page.$$eval() 方法

¥Page.$$eval() method

此方法返回与选择器匹配的所有元素,并将结果数组作为第一个参数传递给 pageFunction

¥This method returns all elements matching the selector and passes the resulting array as the first argument to the pageFunction.

签名

¥Signature

class Page {
$$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>>>

调用 pageFunction 的结果。如果它返回一个元素,则将其封装在 ElementHandle 中,否则返回原始值本身。

¥The result of calling pageFunction. If it returns an element it is wrapped in an ElementHandle, else the raw value itself is returned.

备注

¥Remarks

如果 pageFunction 返回一个 Promise,$$eval 将等待 Promise 解析,然后返回其值。

¥If pageFunction returns a promise $$eval will wait for the promise to resolve and then return its value.

示例 1

¥Example 1

// get the amount of divs on the page
const divCount = await page.$$eval('div', divs => divs.length);

// get the text content of all the `.options` elements:
const options = await page.$$eval('div > span.options', options => {
return options.map(option => option.textContent);
});

如果你使用 TypeScript,则可能必须为 pageFunction 的第一个参数提供显式类型。默认情况下,它的类型为 Element[],但你可能需要提供更具体的子类型:

¥If you are using TypeScript, you may have to provide an explicit type to the first argument of the pageFunction. By default it is typed as Element[], but you may need to provide a more specific sub-type:

示例 2

¥Example 2

await page.$$eval('input', elements => {
return elements.map(e => e.value);
});

编译器应该能够从你提供的 pageFunction 推断出返回类型。如果无法,你可以使用泛型类型告诉编译器你期望从 $$eval 获得什么返回类型:

¥The compiler should be able to infer the return type from the pageFunction you provide. If it is unable to, you can use the generic type to tell the compiler what return type you expect from $$eval:

示例 3

¥Example 3

const allInputValues = await page.$$eval('input', elements =>
elements.map(e => e.textContent)
);