首页 > 解决方案 > 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 秒评估一次页面本身。

但它们不适合我的需要。所以知道如何克服这个问题吗?

标签: puppeteermutation-observerspuppeteer-cluster

解决方案


推荐阅读