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
范围 🌐 Parameter | 类型 🌐 Type | 描述 🌐 Description |
|---|---|---|
pageFunction | 函数 | 字符串 🌐 Func | string | 在页面内运行的函数 🌐 a function that is run within the page |
args | 参数 🌐 Params | 要传递给 pageFunction 的参数 🌐 arguments to be passed to the pageFunction |
返回:
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:
const bodyHandle = await page.$('body');
const html = await page.evaluate(body => body.innerHTML, bodyHandle);
await bodyHandle.dispose();