在 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
有办法实现吗?
最佳答案
目前这是不可能的。但是您可以简单地借助传播到参数来转换 elemetHandles 数组,然后使用剩余运算符将它们再次收集到数组中:
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();
})();
关于javascript - Puppeteer : send array of elementHandle to page. 评估,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49060765/