Page.evaluateHandle() 方法
🌐 Page.evaluateHandle() method
语法
🌐 Signature
class Page {
evaluateHandle<
Params extends unknown[],
Func extends EvaluateFunc<Params> = EvaluateFunc<Params>,
>(
pageFunction: Func | string,
...args: Params
): Promise<HandleFor<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<HandleFor<Awaited<ReturnType<Func>>>>
附注
🌐 Remarks
page.evaluate 和 page.evaluateHandle 唯一的区别在于 evaluateHandle 会返回封装在页面内对象中的值。
🌐 The only difference between page.evaluate and page.evaluateHandle is that evaluateHandle will return the value wrapped in an in-page object.
如果传递给 page.evaluateHandle 的函数返回一个 Promise,该函数将等待该 Promise 被解决并返回其值。
🌐 If the function passed to page.evaluateHandle returns a Promise, the function will wait for the promise to resolve and return its value.
你可以传递字符串而不是函数(尽管建议使用函数,因为它们更容易调试并与 TypeScript 一起使用):
🌐 You can pass a string instead of a function (although functions are recommended as they are easier to debug and use with TypeScript):
示例 1
🌐 Example 1
const aHandle = await page.evaluateHandle('document');
示例 2
🌐 Example 2
JSHandle 实例可以作为参数传递给 pageFunction:
const aHandle = await page.evaluateHandle(() => document.body);
const resultHandle = await page.evaluateHandle(body => body.innerHTML, aHandle);
console.log(await resultHandle.jsonValue());
await resultHandle.dispose();
大多数情况下,这个函数返回一个 JSHandle,但是如果 pageFunction 返回一个元素的引用,你则会得到一个 ElementHandle :
🌐 Most of the time this function returns a JSHandle, but if pageFunction returns a reference to an element, you instead get an ElementHandle back:
示例 3
🌐 Example 3
const button = await page.evaluateHandle(() =>
document.querySelector('button'),
);
// can call `click` because `button` is an `ElementHandle`
await button.click();
TypeScript 的定义假设 evaluateHandle 返回一个 JSHandle,但如果你知道它会返回一个 ElementHandle,请将其作为泛型参数传递:
🌐 The TypeScript definitions assume that evaluateHandle returns a JSHandle, but if you know it's going to return an ElementHandle, pass it as the generic argument:
const button = await page.evaluateHandle<ElementHandle>(...);