木偶:点击

时间:2020-09-11 11:52:28

标签: node.js web-scraping puppeteer

我试图单击一个元素,直到该给定元素从DOM中消失,但这似乎会使浏览器挂起。

这是一个代码段,目标是通过单击“下一步”按钮直至其消失来实际对网站进行分页。(分页结束)

  const jobs = await page.evaluate(
    (container, next) => {
      let next_page = document.querySelector(next);
      while (next_page !== null) {
        next_page.click();
      }
      return true;
    },
    container,
    next
  );

此外,由于元素实际上在特定点从DOM中消失,因此循环似乎不是无限的。

1 个答案:

答案 0 :(得分:2)

您需要在每次迭代后获取next_page元素,否则您将永远无法获取null值才能退出while循环。

const jobs = await page.evaluate(
  (container, next) => {
    let next_page;
    do {
      next_page = document.querySelector(next);
      next_page.click();
    } while (next_page !== null);
    return true;
  },
  container,
  next
);