Pupeteer:将elementHandle数组发送到page.evaluate

时间:2018-03-02 00:08:08

标签: javascript browser puppeteer

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

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

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

1 个答案:

答案 0 :(得分: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();
})();