[英]Puppeteer - Click a button only if exists
I'm trying to create a webscraper in Node, using Puppeteer.我正在尝试使用 Puppeteer 在 Node 中创建一个网络爬虫。 My first challange (which I thought would be easy), it's pass by a pagination "Load more" button.我的第一个挑战(我认为这很容易),它通过分页“加载更多”按钮传递。
But, when I run the following code, Puppeteer click on all "Load more" and after click on a content, when I need to stop clicking.但是,当我运行以下代码时,Puppeteer 单击所有“加载更多”并单击内容后,当我需要停止单击时。
Why this happens?为什么会发生这种情况?
let loadMore = true;
while (loadMore) {
selector = 'ul.pager > li > a.button';
await page.waitForSelector(selector, { timeout: 600 }).then(() => {
page.click(selector);
}).catch(() => {
loadMore = false;
});
}
Thx all!谢谢大家!
I would do it like this.我会这样做。 I think timeout doesn't make a difference here, if the await
inside the if's condition is not enough then there could be other problem with the script.我认为超时在这里没有什么区别,如果 if 条件中的await
不够,那么脚本可能还有其他问题。
let loadMore = true;
while (loadMore) {
const selector = 'ul.pager > li > a.button';
if ((await page.$(selector)) !== null) {
await page.click(selector);
} else {
loadMore = false;
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.