puppeteer page.evaluate querySelectorAll返回空对象

Abd*_*gar 10 javascript node.js puppeteer

我正在尝试木偶操作,这是一个示例代码,您可以在https://try-puppeteer.appspot.com/上运行它

问题是这段代码返回一个空对象数组

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

我有什么不对吗?

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();
Run Code Online (Sandbox Code Playgroud)

Abd*_*gar 24

evaluate函数返回的值应为json serializeable. https://github.com/GoogleChrome/puppeteer/issues/303#issuecomment-322919968

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

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


Gra*_*ler 12

问题:

的返回值page.evaluate()必须是可序列化的

根据Puppeteer 文档,它说:

如果传递给 的函数page.evaluate返回一个不可序列化的值,则page.evaluate解析为undefined。DevTools协议还支持转移是不可序列通过一些附加价值JSON-0NaNInfinity-Infinity,和BIGINT文字。

换句话说,您不能将页面 DOM 环境中的元素返回到 Node.js 环境,因为它们是分开的。

解决方案:

您可以将一个ElementHandle,它是页面内 DOM 元素的表示形式,返回到 Node.js 环境。

使用page.$$()以获得ElementHandle阵列:

let list = await page.$$('.title');
Run Code Online (Sandbox Code Playgroud)

否则,如果您想href从元素中提取值并返回它们,您可以使用page.$$eval()

let list = await page.$$eval('.title', a => a.href);
Run Code Online (Sandbox Code Playgroud)


Can*_*Ali 8

我遇到了类似的问题,我是这样解决的;

 await page.evaluate(() => 
       Array.from(document.querySelectorAll('.title'), 
       e => e.href));
Run Code Online (Sandbox Code Playgroud)

  • TIL `Array.From` 采用回调映射函数 (3认同)