我正在使用 puppeteer 进行一些测试。
没有编写代码,因为我什至不知道如何解决这个问题。
• I have a list of 10 IDs inside an array
• For each ID - a new page/tab is opened
• I want to run the script for each page/ tab without having to wait for the previous page/tab
to finish before starting the next. Hence the simultaneous execution.
那么 10 个页面将同时运行相同的脚本?
这可以通过 Javascript 和 puppeteer 实现吗?
最佳答案
您可能想查看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();
})();
关于javascript - 如何与 Puppeteer/Javascript 同时运行脚本?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62158922/