迭代页面中的链接,并根据条件单击



我正在删除一个网页,我只需要在该页面上下载符合某些条件的文件。我该如何在木偶中实现?

我能够使用选择器找到元素并使用page.$$eval抓住我需要的属性,但是我无法弄清楚如何单击该链接。

const sectionLinks = await page.$$eval('#mainsection a', aTags => aTags.map(a => a.innerText));
  for (const sectionLink of sectionLinks) {
    if (sectionLink.toUpperCase() == 'THEONEIWANT') {
      console.log('download');
      //this is where I want to click the link
    }
  }

您没有得到元素句柄。您只返回其innerText值。

您能做的是,首先获取所有元素,然后像这样迭代它们:

const elements = await page.$$('#mainsection a');
for (const el of elements) {
    const innerText = await page.evaluate(el => el.innerText, el);
    if (innerText.toUpperCase() == 'THEONEIWANT') {
        await el.click();
    }
}

这将逐一遍历所有元素,阅读其innerText值,检查条件是否匹配,然后单击它。

优化

如果有很多链接,这可能需要一些时间。您可以使用基于您要查找的文本匹配的选择器来改进此代码(查看此问题以获取更多信息(或使用以下表达式来检查条件是否匹配客户端端。这将对所有元素进行检查:

const shouldElementBeClicked = page.evaluate((...args) => args.map(el => el.innerText === '...'), ...elements);

这将导致带有布尔值的数组信号传导是否满足elements数组中相同位置的元素是否满足条件。

最新更新