javascript - 如何将 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();
}
})();
});
解决方案
正如您已经注意到的,您的代码会并行启动所有浏览器,这会使您的系统过载。您可以一个接一个地访问每个 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/内存)使用 的值来更改工作人员的数量。
推荐阅读
- c# - 有没有办法使用 xamarin Forms 访问设备浏览器数据?
- view - 如何根据 SwiftUI 中另一个视图的变量显示一个视图(在 ContentView 中)?
- python - Gmail API - ModuleNotFoundError:没有名为“googleapiclient”的模块 - Python 3.7
- r - 为什么我不能在 R 中将 tibble 转换为数据框?
- python - 为什么 Django 模板会阻止 HTML 自动完成功能?
- python - 尝试安装 MySQL 客户端时,导入 sys、setuptools、tokenize 时出现此错误
- kotlin - Kotlin 中的管道
- node.js - Nodemon 在每次更改时重新启动,而不是在保存时
- sql - 插入更新另一个表后创建触发器
- angular - Vanilla ASP.NET Core 项目对每个请求都有 2 秒的延迟