【问题标题】:Iterate over links in a page and click based on condition遍历页面中的链接并根据条件单击
【发布时间】:2019-05-23 00:48:41
【问题描述】:

我正在抓取一个网页,我只需要下载该网页上符合特定条件的文件。如何在 puppeteer 中实现这一点?

我可以使用选择器定位元素并使用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
    }
  }

【问题讨论】:

    标签: javascript node.js puppeteer


    【解决方案1】:

    你没有得到元素句柄。您只返回他们的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值,检查条件是否匹配,然后单击它。

    优化

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

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

    这将产生一个带有布尔值的数组,表明elements 数组中相同位置的元素是否满足条件。

    【讨论】:

      猜你喜欢
      • 2011-11-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-10-02
      • 2020-01-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多