javascript - 我怎样才能使用 puppeteer 作为 cachewarmer?

标签 javascript node.js web-scraping puppeteer

我有一个很长的 txt 文件,其中包含约 1000 个 url,需要执行它来预热 varnish 缓存。
由于我需要 puppeteer,是否存在通过 AJAX 调用加载的重要内容。

这是我的第一次尝试,但不是 node 的高手。
真正的问题是它产生了 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();
    }

})();
});

最佳答案

正如您已经注意到的,您的代码会并行启动所有浏览器,这会使您的系统过载。您可以一个接一个地访问每个 URL(选项 1)或使用 pool of browsers加快流程(选项 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/内存)更改工作程序的数量。

关于javascript - 我怎样才能使用 puppeteer 作为 cachewarmer?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55057539/

相关文章:

javascript - JavaScript 中的所有事件监听器如何保持事件状态?

javascript - 什么时候在 Nodejs 中使用匿名函数?

javascript - 如何拆分从网站上抓取的文本?

node.js - 如果不存在,则创建并添加到集合 sails.js

python - 使用动态鼠标悬停事件抓取网站

python - 无法使用请求从下一页中抓取姓名

javascript - Eslint: no-duplicates 解决错误:无法加载解析器 "node"

javascript - jQuery:具有相同名称的项目/类

javascript - 如何使动画仅在可见时工作

javascript - 来自 php 文件的 xampp 脚本不会转移到 html 文件