我使用 node.js
与 puppeteer
结合创建了一个脚本,用于点击更多
按钮位于网页底部,可从其着陆页中挖掘出所有标题。
问题是,当我执行脚本时,它只单击一次,然后退出。我怎样才能继续点击该按钮,直到没有更多的按钮可以点击,这意味着所有链接都被显示出来?
到目前为止我的尝试:
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.js
和 puppeteer
的新手,我无法理解如何定义循环来完成任务。
最佳答案
在这种情况下,我经常做的是使用 try catch
block 来检查元素的可见性,使用 waitForSelector
并使用非常短的超时。您需要 try catch
block ,因为当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();
})();
关于javascript - 无法让我的脚本不断点击按钮,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52976730/