Skip to main content
Version: 23.2.0

Page.evaluate() 方法

¥Page.evaluate() method

评估页面上下文中的函数并返回结果。

¥Evaluates a function in the page's context and returns the result.

如果传递给 page.evaluate 的函数返回 Promise,该函数将等待 Promise 解析并返回其值。

¥If the function passed to page.evaluate returns a Promise, the function will wait for the promise to resolve and return its value.

签名

¥Signature

class Page {
evaluate<
Params extends unknown[],
Func extends EvaluateFunc<Params> = EvaluateFunc<Params>,
>(
pageFunction: Func | string,
...args: Params
): Promise<Awaited<ReturnType<Func>>>;
}

参数

¥Parameters

范围

类型

描述

pageFunction

功能 | 字符串

在页面内运行的函数

args

参数

要传递给 pageFunction 的参数

Returns:

Promise<Awaited<ReturnType<Func>>>

pageFunction 的返回值。

¥the return value of pageFunction.

示例 1

¥Example 1

const result = await frame.evaluate(() => {
return Promise.resolve(8 * 7);
});
console.log(result); // prints "56"

你可以传递字符串而不是函数(尽管建议使用函数,因为它们更容易调试并与 TypeScript 一起使用):

¥You can pass a string instead of a function (although functions are recommended as they are easier to debug and use with TypeScript):

示例 2

¥Example 2

const aHandle = await page.evaluate('1 + 2');

为了获得最佳的 TypeScript 体验,你应该传入 pageFunction 的泛型类型:

¥To get the best TypeScript experience, you should pass in as the generic the type of pageFunction:

const aHandle = await page.evaluate(() => 2);

示例 3

¥Example 3

ElementHandle 实例(包括 JSHandle)可以作为参数传递给 pageFunction

¥ElementHandle instances (including JSHandles) can be passed as arguments to the pageFunction:

const bodyHandle = await page.$('body');
const html = await page.evaluate(body => body.innerHTML, bodyHandle);
await bodyHandle.dispose();