Puppeteer 返回空对象 [英] Puppeteer returning empty object

查看:52
本文介绍了Puppeteer 返回空对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我在页面控制台中运行以下代码时,我试图抓取,我得到了 图片.

When I run the following code in the page console I'm trying to scrape, I got picture.

document.querySelector('#sb-site > div.sticky_footer > div:nth-child(9)')

但是,当我在我的程序中运行它时,控制台会记录它并返回{}"

However, when I run this in my program, the console log it and returns '{}'

const inputContent = await page.evaluate(() => {
return document.querySelector('#sb-site > div.sticky_footer > div:nth-child(9)'); });

推荐答案

puppeteer 可以在 Node.js 和浏览器上下文之间传输两种类型的数据:可序列化数据(即 JSON.stringify()/JSON.parse()) 和 JavaScript 对象 ID(包括 DOM 元素)——JSHandle 和 ElementHandle.后面的 API 有点复杂(参见 JSHandle 和 ElementHandle 方法或提到它们的方法).

puppeteer can transfer two types of data between Node.js and browser context: serializable data (i.e. data that is supported by JSON.stringify()/JSON.parse()) and JavaScript object ids (including DOM elements) — JSHandle and ElementHandle. Later ones have a bit more complicated API (see JSHandle and ElementHandle methods or methods that mention them).

page.evaluate() 只能传输可序列化的数据,而不是不可序列化的数据,它返回 undefined 或空对象.DOM 元素是不可序列化的,因为它们包含循环引用和方法.

page.evaluate() can only transfer serializable data, and instead of un-serializable data, it returns undefined or empty objects. DOM elements are non-serializable as they contain circular references and methods.

因此,如果您只需要一些文本或元素属性,请尝试在浏览器上下文中进行大部分处理并仅返回可序列化的数据.

So if you just need some text or element attributes, try to do most of the processing in the browser context and return just serializable data.

这篇关于Puppeteer 返回空对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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