如何解决使用箭头函数进入 puppeter 脚本的 page.evaluate 的返回块
这可能是 Promise 的问题:
看看我的返回块的 since
字段,
使用箭头函数它不会返回任何结果:
{
link: 'www.xxxxxx.com/1234',name: 'jhon doe',since: {}
},
不是直接返回值,而是按预期工作!
由于我需要使用选择器执行复杂的操作,所以我想在这一点上使用内联箭头函数,我该如何解决才能得到结果?
let rawMembers = await page.evaluate(() => new Promise((resolve) => {
....
//captute all the link
const anchors = Array.from(document.querySelectorAll('a'));
let result = anchors.map(x => {
return {
link: x.getAttribute("href"),name: x.innerText,//since : x.parentNode.parentNode.parentNode.parentNode.getAttribute("class") <--- this works
since: x => { <---using an arrow function,it returns and empty objecy `{}`
// i need a function here to do complex and multiline operations
return x.parentNode.parentNode.parentNode.parentNode.getAttribute("class");
}
....
resolve(results);
我也试过了,但结果相同
since: x => new Promise((resolve) => {
// i need a function here to do complex and multiline operations
resolve(x.parentNode.parentNode.parentNode.parentNode.getAttribute("class"));
})
解决方法
在 since
中,您引用了箭头函数本身,而不是其结果。函数不可序列化,因此您会得到一个空对象。您需要调用该函数,即使用 IIFE:
since: (() => {
return x.parentNode.parentNode.parentNode.parentNode.getAttribute("class");
})()
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。