Page.$eval() 方法
¥Page.$eval() method
此方法查找页面中与选择器匹配的第一个元素,并将结果作为第一个参数传递给 pageFunction
。
¥This method finds the first element within the page that matches the selector and passes the result as the first argument to the pageFunction
.
签名
¥Signature
class Page {
$eval<
Selector extends string,
Params extends unknown[],
Func extends EvaluateFuncWith<NodeFor<Selector>, Params> = EvaluateFuncWith<
NodeFor<Selector>,
Params
>,
>(
selector: Selector,
pageFunction: Func | string,
...args: Params
): Promise<Awaited<ReturnType<Func>>>;
}
参数
¥Parameters
范围 | 类型 | 描述 |
---|---|---|
selector | 选择器 | 要查询页面的 selector。CSS 选择器 可以按原样通过,并且 Puppeteer 特定的选择器语法 允许通过 text、a11y 角色和名称、xpath 和 跨影子根组合这些查询 进行查询。或者,你可以使用 prefix 指定选择器类型。 |
pageFunction | 功能 | 字符串 | 要在页面上下文中评估的函数。将传递与选择器匹配的元素的结果作为其第一个参数。 |
args | 参数 | 传递给 |
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
如果没有找到与 selector
匹配的元素,该方法将抛出错误。
¥If no element is found matching selector
, the method will throw an error.
如果 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
const searchValue = await page.$eval('#search', el => el.value);
const preloadHref = await page.$eval('link[rel=preload]', el => el.href);
const html = await page.$eval('.main-container', el => el.outerHTML);
如果你使用 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
// if you don't provide HTMLInputElement here, TS will error
// as `value` is not on `Element`
const searchValue = await page.$eval(
'#search',
(el: HTMLInputElement) => el.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
// The compiler can infer the return type in this case, but if it can't
// or if you want to be more explicit, provide it as the generic type.
const searchValue = await page.$eval<string>(
'#search',
(el: HTMLInputElement) => el.value,
);