Puppeter为page.evaluate返回undefined,尽管已在devtools上解决



我有一个简单的代码,我希望在其中找到包含特定文本的元素,例如

await page.goto('https://www.reddit.com/r/koreanvariety/comments/hsdt4j/the_great_escape_season_3_e12_back_to_the/')

await page.waitFor(2000);
const findComment = await page.evaluate(() => {
return Array.from(document.querySelectorAll('a')).find(el => el.textContent === 'sometext' )
})
console.log('findComment', findComment)

尽管上面的代码适用于devtools,但它在我的windows控制台中返回undefined

我相信在发出此请求时页面尚未完全加载,但在等待page.waitFor(2000);时,我无法返回任何结果。

如何从page.evaluate获取数据?

这是预期行为

为了从page.evaluate获取数据,必须返回可序列化的值,即可以用JSON.stringify字符串化的值。

来自文件:

如果传递给page.evaluate的函数返回一个不可序列化的值,则page.evalvate解析为undefined。

解决方案

整个DOM节点(您在脚本中找到的(无法序列化,因为它具有循环引用。您必须从节点中选择您想要的数据,并明确返回这些数据:

const findComment = await page.evaluate(() => {
return Array.from(document.querySelectorAll('a')).find(el => el.textContent === 'sometext' )?.href
})

相关内容

最新更新