Puppeteer:将元素句柄数组发送到page.evaluate

问题描述 投票:0回答:1

在Pupeteer中,我想将任意数量的ElementHandle传递给数组中的方法evaluate:

const element1=await page.$(".element")
const element2=await page.$(".another-element")

await page.evaluate((elements)=>{
  // do stuff with the array of elements
,[element1, element2]);

但是,因为ElementHandle不可序列化,会出现以下错误:

TypeError: Converting circular structure to JSON

有没有办法实现这个目标?

javascript browser puppeteer
1个回答
1
投票

目前这是不可能的。但你可以简单地转换你的elemetHandles数组,借助传播到参数,然后使用rest运算符将它们再次收集到数组中:

const puppeteer = require('puppeteer');

const html = `
<html>
    <body>
        <div class="element">element 1</div>
        <div class="element">element 2</div>
        <div class="element">element 3</div>
    </body>
</html>`;

(async () => {
    const browser = await puppeteer.launch();
    const page = await browser.newPage();
    await page.goto(`data:text/html,${html}`);

    const element1 = await page.$('.element:nth-child(1)');
    const element2 = await page.$('.element:nth-child(2)');
    const element3 = await page.$('.element:nth-child(3)');

    const result = await page.evaluate((...elements) => {
        // do stuff with the array of elements
        return elements.map(element => element.textContent);
    }, ...[element1, element2, element3]);

    console.log(result);
    await browser.close();
})();
© www.soinside.com 2019 - 2024. All rights reserved.