首页 > 解决方案 > 如何处理 puppeteer-cluster[CONCURRENCY_BROWSER] 中的多个选项卡?

问题描述

我正在尝试在以下条件下抓取 3 个网址

  1. 每个 url 需要在单独的浏览器中运行。

  2. 网址可能包含 2 个或更多要点击的链接

  3. 在相应浏览器(并行)的新选项卡中打开链接并切换到它并抓取内容。

换句话说,我试图在浏览器中打开一个 url,获取页面中的链接,根据在同一浏览器中获取的链接数量打开新选项卡,切换选项卡单击其中的按钮并获取确认消息。

我还需要并行运行 3 个 url。

我尝试了 CONCURRENCY_BROWSER 选项来并行运行 url,但我无法在新选项卡中打开链接。关于如何操作 puppeteer-cluster 中的选项卡的任何建议

我需要的是:

async function test(){
    const cluster = await Cluster.launch({
        puppeteerOptions: {
            headless: false,
            defaultViewport: null, 
        },
      
        concurrency: Cluster.CONCURRENCY_BROWSER,
        maxConcurrency: 5,
        skipDuplicateUrls : true,
        timeout : 240000,
    });

    // initiate the cluster task for a set of urls from the cluster queue;
    
    await page.goto(url);
    
    // on visiting the page i retrieve 2 or more links and store it in a array
    
    let linksArray = [...subUrl];
    
    //load suburl in a new tab respectively of the same browser

    await cluster.newPage()

    //screenshot suburl
    
    await page.screenshot(suburl)
        
}

类型错误:cluster.newPage 不是函数

在 puppeteer 中,我曾经使用命令 await browser.newPage() 打开一个新选项卡

标签: javascriptnode.jspuppeteerpuppeteer-cluster

解决方案


这里的作者puppeteer-cluster。重复使用相同的浏览器并不容易。但是,您可以像这样定义一个包含多个page.goto调用的任务:

const cluster = await Cluster.launch(/* ... */);

// define the task and reuse the window 
await cluster.task(async ({ page, data: url }) => {
    await page.goto(url);
    const secondUrl = /* ... */; // extract another URL somehow
    await page.goto(secondUrl);
    await page.screenshot(/* ... */);
});

// queue your initial links
cluster.queue('http://...');
cluster.queue('http://...');
// ...

推荐阅读