Pupeteer:将elementHandle数组发送到page。评估

2022-03-11 00:00:00 puppeteer browser javascript

在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

有没有办法实现这一点?


解决方案

目前无法执行此操作。但是,您可以简单地借助扩散到参数来转换elemetHandle数组,然后使用睡觉运算符将它们重新收集到数组中:

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();
})();

相关文章