我创建了一个脚本,使用more与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并不熟悉,所以我不明白如何定义一个循环来完成任务。
发布于 2018-10-24 20:44:50
在这种情况下,我经常做的是使用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();
})();发布于 2018-10-24 20:37:24
只需添加一个使单击的命令的循环,例如:
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();
})();https://stackoverflow.com/questions/52976730
复制相似问题