木偶页面.评估querySelectorAll返回空对象 [英] Puppeteer page.evaluate querySelectorAll return empty objects

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

问题描述

我正在尝试Puppeteer.这是可以在其上运行的示例代码: https://try-puppeteer.appspot.com/

I am trying out Puppeteer. This is a sample code that you can run on: https://try-puppeteer.appspot.com/

问题在于此代码返回一个空对象数组:

The problem is this code is returning an array of empty objects:

[{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{ },{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{}, {},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{} ,{},​​{},{},{},{},{},{},{}]

[{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{}]

我犯错了吗?

const browser = await puppeteer.launch();

const page = await browser.newPage();
await page.goto('https://reddit.com/');

let list = await page.evaluate(() => {
  return Promise.resolve(Array.from(document.querySelectorAll('.title')));
});

console.log(JSON.stringify(list))

await browser.close();

推荐答案

valuate函数返回的值应该是json可序列化的. https://github.com/GoogleChrome/puppeteer/issues/303#issuecomment-322919968

The values returned from evaluate function should be json serializeable. https://github.com/GoogleChrome/puppeteer/issues/303#issuecomment-322919968

解决方案是从元素中提取href值并将其返回.

the solution is to extract the href values from the elements and return it.

 await this.page.evaluate((sel) => {
        let elements = Array.from(document.querySelectorAll(sel));
        let links = elements.map(element => {
            return element.href
        })
        return links;
    }, sel);

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

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