puppeteer - puppeteer集群_如何防止关闭页面?
问题描述
我很高兴找到 puppeteer 集群。这个库使爬行和自动化任务的生活变得轻松。tnx to Thomas Dondorf。
根据 puppeteer 集群的作者所说,当任务完成时页面将立即关闭。顺便说一句,这很好。但是,您需要分页的某些情况如何?
我的用例:我将尝试简要解释一下:
页面上有一些活动,在后台涉及一个套接字,用于将一些数据发送到前面。这个数据改变了圆顶,我需要捕获它。
这是我的代码:
async function runCrawler(){
const links = [
"foo.com/barSome324",
"foo.com/barSome22",
"foo.com/barSome1",
"foo.com/barSome765",
]
const cluster = await Cluster.launch({
concurrency: Cluster.CONCURRENCY_CONTEXT,
workerCreationDelay: 5000,
puppeteerOptions:{args: ['--no-sandbox', '--disable-setuid-sandbox'], headless:false},
maxConcurrency: numCPUs,
});
await cluster.task(async ({ page, data: url }) => {
await crawler(page, url)
});
for(link of links){
await cluster.queue(link);
}
await cluster.idle();
await cluster.close();
}
这是页面部分的爬虫逻辑:
module.exports.crawler = async(page, link)=>{
await page.goto(link, { waitUntil: 'networkidle2' })
await page.waitForTimeout(10000)
await page.waitForSelector('#dbp')
try {
// method to be executed;
setInterval(async()=>{
const tables=await page.evaluate(async()=>{
/// data I need to catch in every 30 seconds
});
},30000)
} catch (error) {
console.log(error)
}
}
我搜索并发现在 js 中我们可以使用mutationObserver捕获 DOM 更改。并尝试了这个解决方案。但也没有工作。页面将因以下错误而关闭:
UnhandledPromiseRejectionWarning:错误:协议错误(Runtime.callFunctionOn):会话关闭。该页面很可能已关闭。
所以我在这里有两个选择:
1.mutationObserver
2.set interval 每 30 秒评估一次页面本身。
但它们不适合我的需要。所以知道如何克服这个问题吗?
解决方案
推荐阅读
- reactjs - store.getState 总是返回默认状态
- python - /esacp/profile/ 中的 RelatedObjectDoesNotExist 用户在 Django 中没有配置文件
- android - 某些设备上的 Android 布局太大
- azure - 无法从 Azure VM 中运行的 Windows 服务访问 Azure 文件共享
- java - 为什么我的纯 NIO selectKey 仍然选择了事件
- javascript - 防止在 iOS 13 / Mobile Safari 上点击并按住文本选择
- python - mypy 键入导致意外回溯
- reactjs - 如何在 React 应用程序中获取谷歌地图 api 输入字段的状态更新
- python - 请求多个网站的 Python 类
- django - 具有多对多关系的 DRF 2 路嵌套序列化