首页 > 解决方案 > 如何将 puppeteer 用于 cachewarmer?

问题描述

我有一个txt大约 1000 个 url 的长文件,需要执行它来加热清漆缓存。
由于我需要 puppeteer,是不是有通过 AJAX 调用加载的重要内容。

这是我的第一次尝试,但不是节点中的主人。
真正的问题是它产生了 100% 的负载,并且启动了太多线程。

const puppeteer = require('puppeteer');
const readline = require('readline');
const fs = require('fs');

const rl = readline.createInterface({
    input: fs.createReadStream('varnish-warmer.txt')
  });

rl.on('line', (line) => {
(async () => {
    if (line != '') {
    const browser = await puppeteer.launch();
        const page = await browser.newPage();
        await page.goto(line);
        await page.waitFor(1000);

        browser.close();
    }

})();
});

标签: javascriptnode.jsweb-scrapingpuppeteer

解决方案


正如您已经注意到的,您的代码会并行启动所有浏览器,这会使您的系统过载。您可以一个接一个地访问每个 URL(选项 1),也可以使用浏览器池来加快处理速度(选项 2)。

选项1

启动一个浏览器并依次访问所有页面:

const puppeteer = require('puppeteer');
const fs = require('fs');

const lines = fs.readFileSync('varnish-warmer.txt').toString().split('\n');

(async () => {
    const browser = await puppeteer.launch();
    const page = await browser.newPage();
    for (const line of lines) {
        await page.goto(line);
        await page.waitFor(1000);
    }
    await browser.close();
})();

选项 2

由于选项 1 可能需要一段时间来处理 1000 个 URL,因此您可能希望使用浏览器池来并行访问页面并加快速度。您可以为此使用puppeteer-cluster(免责声明:我是该库的作者)。

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

(async () => {
    const cluster = await Cluster.launch({
        concurrency: Cluster.CONCURRENCY_BROWSER,
        maxConcurrency: 10, // how many URLs should be visited in parallel
        // monitor: true, // uncomment to see information about progress
    });

    // Define the task for each URL
    await cluster.task(async ({ page, data: url }) => {
        await page.goto(url);
        await page.waitFor(1000);
    });

    // Queue the URLs
    const lines = fs.readFileSync('varnish-warmer.txt').toString().split('\n');
    lines.forEach(line => cluster.queue(line));

    // Wait for the tasks to finish and close the cluster after that
    await cluster.idle();
    await cluster.close();
})();

您可以maxConcurrency根据系统的功能(CPU/内存)使用 的值来更改工作人员的数量。


推荐阅读