我现在正在使用player,我想写一个包含内部箭头函数的函数,类似
async function setSearchDate(startDate='2021-12-07') {
....do something...
const startDateAttribute = await page.$(searchStartDate);
await startDateAttribute.evaluate(node => node.setAttribute('value', startDate));
但不知何故,内部箭头函数看不到startDate值。我得到的错误是";elementHandle.evaluate:ReferenceError:startDate未定义"。
如果我在箭头函数中硬编码startDate值,则代码运行良好。如何传递该值?
evaluate
在页面中评估函数,而不是在代码的上下文中。您可以访问页面执行环境中存在的所有内容(例如window
、document
等(,但不能访问您的执行环境中不存在的任何内容(例如,startDate
(。这是因为在页面的上下文中,没有变量startDate
(除非页面定义了自己的window.startDate
…(
要传递参数,您必须使用...args
-evaluate
获取额外的参数,这些参数都会传递给您的函数:
await startDateAttribute.evaluate(
(node, startDate) => node.setAttribute('value', startDate),
// ^^^^^^^^^ 2) extra argument(s) arrive here
//vvvvvvvvv 1) extra argument(s) getting passed in here
startDate
)
请参阅文档:评估JavaScript(解释这个确切的陷阱(和ElementHandle#evaluate
。
await startDateAttribute.evaluate(function(node) { node.setAttribute('value', startDate) });