您可能想查看puppeteer-cluster(我是该库的作者),它支持您的用例。该库并行运行任务,但也负责错误处理、重试和其他一些事情。
您还应该记住,为 10 个 URL 打开 10 个页面在 CPU 和内存方面非常昂贵。您可以改用puppeteer-cluster浏览器或页面池。
代码示例
您可以在下面看到一个最小的示例。也可以在更复杂的设置中使用该库。
const { Cluster } = require('puppeteer-cluster');
(async () => {
const cluster = await Cluster.launch({
concurrency: Cluster.CONCURRENCY_PAGE, // use one browser per worker
maxConcurrency: 4, // Open up to four pages in parallel
});
// Define a task to be executed for your data, this function will be run for each URL
await cluster.task(async ({ page, data: url }) => {
await page.goto(url);
// ...
});
// Queue URLs (you can of course read them from an array instead)
cluster.queue('http://www.google.com/');
cluster.queue('http://www.wikipedia.org/');
// ...
// Wait for cluster to idle and close it
await cluster.idle();
await cluster.close();
})();