让 Puppeteer 同时访问不同的链接

chr*_*321 2 javascript node.js web-scraping puppeteer

我需要让我的 api 能够更快地抓取 URL 列表。现在,我一次转到每一页并将数据添加到数组中。我需要一次打开多个链接并将从中获取的数据添加到同一个数组中。

这是我的代码:

var videos = [];
        for(var i = 0; i < profile.videoLinks.length; i++){
            await page.goto(profile.videoLinks[i].video, {
                // waitUntil: 'load'
            });
            await page.waitForSelector('.music-info')
            var vidInfo = await page.evaluate(() => {
                const vidTitle = document.querySelector('.video-meta-title').innerText;
                const musicInfo = document.querySelector('.music-info').innerText;
                const musicLink = document.querySelector('.music-info a').href;
                const likes = document.querySelector('.like-text').innerText;
                const comments = document.querySelector('.comment-text').innerText;

                return {
                    vidTitle,
                    musicInfo,
                    musicLink,
                    likes,
                    comments
                }
            })
            videos.push(vidInfo);
Run Code Online (Sandbox Code Playgroud)

现在,我的链接数组位于profile.videoLinks[ ].video. 我应该将数组分成两半然后对每个数组使用评估函数吗?

Tho*_*orf 5

您可以使用puppeteer-cluster并行运行任务(我是该库的作者)。您可以指定要并行使用的页面(或浏览器)数量。然后,库会负责运行您的任务。

代码示例

const { Cluster } = require('puppeteer-cluster');

const videos = [];

(async () => {
    // Setup a cluster with 4 browsers in parallel
    const cluster = await Cluster.launch({
        concurrency: Cluster.CONCURRENCY_BROWSER,
        maxConcurrency: 4,
    });

    // Define your task to be executed
    await cluster.task(async ({ page, data: url }) => {
        await page.goto(url);
        await page.waitForSelector('.music-info');

        var vidInfo = await page.evaluate(/* ... */);
        videos.push(vidInfo);
    });

    // Queue your URLs
    for(var i = 0; i < profile.videoLinks.length; i++){
        cluster.queue(profile.videoLinks[i].video);
    }

    // Wait for the cluster to finish and close it
    await cluster.idle();
    await cluster.close();
})();
Run Code Online (Sandbox Code Playgroud)