尽管在 devtools 上已解决,Puppeteer 仍为 page.evaluate 返回 undefined [英] Puppeteer returns undefined for page.evaluate despite being resolved on devtools

查看:154
本文介绍了尽管在 devtools 上已解决,Puppeteer 仍为 page.evaluate 返回 undefined的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个简单的代码,我希望在其中找到包含某些文本的元素

 await page.goto('https://www.reddit.com/r/koreanvariety/comments/hsdt4j/the_great_escape_season_3_e12_back_to_the/')等待页面.waitFor(2000);const findComment = await page.evaluate(() => {返回 Array.from(document.querySelectorAll('a')).find(el => el.textContent === 'sometext' )})console.log('findComment', findComment)

虽然上面的代码适用于 devtools,但它在我的 Windows 控制台中返回 undefined.

我相信在发出此请求时页面尚未完全加载,但是在求助于 await page.waitFor(2000); 时,我无法获得任何结果.>

如何从 page.evaluate 取回数据?

解决方案

这是预期行为

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

来自文档:

<块引用>

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

解决方案

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

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

I have a simple code in which I expect to find the element that contains certain text as such

  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)

And although the code above works on devtools it returns undefined in my windows console.

I believe the page is not fully loaded by the time this request is made however I have not been able to get any results back when resorting to await page.waitFor(2000);.

How do I get data back from page.evaluate?

解决方案

This is expected behavior

In order to get data from page.evaluate one must return serializable value, i.e. a value that can be stringified with JSON.stringify.

From the documentation:

If the function passed to the page.evaluate returns a non-Serializable value, then page.evaluate resolves to undefined.

Solution

A whole DOM node (that you find in your script) cannot be serialized because it has circular references. You will have to choose which data from the node you want and explicitly return those:

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

这篇关于尽管在 devtools 上已解决,Puppeteer 仍为 page.evaluate 返回 undefined的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆