【问题标题】:how to loop over divs with the same class with Puppeteer如何使用 Puppeteer 遍历具有相同类的 div
【发布时间】:2021-01-27 20:03:24
【问题描述】:

使用 puppeteer 抓取页面我能够从具有相同类的 div 列表和其中的嵌套 div 列表中获取内容,即

<div class="parent">
    <div class="child"></div>
</div>
<div class="parent">
    <div class="child"></div>
    <div class="child"></div>
</div>
<div class="parent">
    <div class="child"></div>
    ...
</div>
...

现在我的问题是我需要重申列表并在子类 div 上运行 page.click() 以打开灯箱,在灯箱中选择一个元素以单击然后运行 ​​page.pdf()。

我目前在父类 div 上有一个 for 循环,在子类 div 上有一个内部 for 循环。我不确定如何使用 for 循环索引值选择正确的 div,因为没有第 n 个类等。

我只是想运行类似的东西

for (let a = 0; a < data.length; a++) {
    for (let b = 0; b < data[a].length; b++) {
        await page.click('.parent[a] .child[b]');
        // other code here...
    }
}

打开灯箱,然后是

await page.waitForSelector('.ReactModal')

抓取灯箱 html 并运行

await page.pdf({
    path: dir + "/"+ filename, 
    format: 'A4' 
});

对于可能的方法,我们将不胜感激。

【问题讨论】:

  • 你也可以像这样在页面中运行 javascript ex await page.evaluate(_ => { var childs = document.querySelectorAll('.child'); [].forEach.call( childs,函数(el){ el.click(); }); });

标签: node.js puppeteer


【解决方案1】:

如果我理解正确,你可以试试这样:

for (const parent of await page.$$('.parent')) {
  for (const child of await parent.$$('.child')) {
    await child.click();
    await page.waitForSelector('.ReactModal'); // maybe check if this is not the same lightbox
    await page.pdf(/*...*/);
  }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-10-04
    • 2012-10-15
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多