【问题标题】:Unable to make my script keep clicking on a button无法让我的脚本继续点击按钮
【发布时间】:2018-10-25 21:22:02
【问题描述】:

我创建了一个脚本,使用 node.jspuppeteer 关联,点击位于网页底部的 more 按钮进行挖掘登陆页面的所有标题。

问题是当我执行我的脚本时,它只单击一次然后退出。我怎样才能一直点击那个按钮,直到没有更多的按钮可以点击,这意味着所有的链接都被显示出来了?

到目前为止我的尝试:

const puppeteer = require("puppeteer");

(async function main() {
    const browser = await puppeteer.launch({headless:false});
    const page = await browser.newPage();
    await page.goto("https://www.newsnow.co.uk/h/Sport/Football/Championship/Transfer+News", {waitUntil: 'networkidle2'});
    await page.waitForSelector("[class^='hl_more']");
    await page.click("[class^='hl_more']");
    await browser.close();
})();

由于我是 node.jspuppeteer 的新手,我无法理解如何定义循环来完成任务。

【问题讨论】:

    标签: javascript node.js web-scraping puppeteer


    【解决方案1】:

    在这种情况下,我经常做的是使用 try catch 块来检查元素的可见性,使用 waitForSelector 并使用非常短的超时。您需要 try catch 块,因为当该 more 按钮不再可见时,waitForSelector 最终会超时。这也是为什么您需要使用较短的特定超时,因为您不希望代码在尝试查找组件时暂停 30 秒(默认超时)。

    所以我会这样做:

    // This method checks if an element is visible and times out cleanly after 2 seconds if it is not displayed
    const isElementVisible = async (page, cssSelector) => {
      try {
        await page.waitForSelector(cssSelector, { timeout: 2000 });
      } catch {
        return false;
      }
      return true;
    };
    
    (async function main() {
      const browser = await puppeteer.launch({headless:false});
      const page = await browser.newPage();
      await page.goto("https://www.newsnow.co.uk/h/Sport/Football/Championship/Transfer+News", {waitUntil: 'networkidle2'});
      let moreDisplayed = await isElementVisible(page, '[class^="hl_more"]');
      while (moreDisplayed) {
        await page.click('[class^="hl_more"]');
        moreDisplayed = await isElementVisible(page, '[class^="hl_more"]');
      }
      await browser.close();
    })();
    

    【讨论】:

    • 这是a.hl_more.bg_tween:not(.nfloading) 选择器,应该用当前的选择器替换以完美地完成这个技巧。顺便说一句,要在括号 catch () 中添加一些内容,以便脚本正常工作。我向未来的读者提出了这个建议。谢谢。
    【解决方案2】:

    只需添加一个点击命令的循环,例如:

    const puppeteer = require("puppeteer");
    
    (async function main() {
        const browser = await puppeteer.launch({headless:false});
        const page = await browser.newPage();
        await page.goto("https://www.newsnow.co.uk/h/Sport/Football/Championship/Transfer+News", {waitUntil: 'networkidle2'});
        await page.waitForSelector("[class^='hl_more']");
        while (1) { // This one
            await page.click("[class^='hl_more']");
        }
        await browser.close();
    })();
    

    Various loop types in JavaScript.

    【讨论】:

      猜你喜欢
      • 2019-07-30
      • 1970-01-01
      • 1970-01-01
      • 2018-01-26
      • 2014-01-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多