javascript - 如何与 Puppeteer/Javascript 同时运行脚本?

标签 javascript asynchronous async-await puppeteer

我正在使用 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/

相关文章:

asynchronous - 有什么原因不能立即取消 Async.Sleep 吗?

c# - 具有异步操作的异步 Controller 不起作用

c# - 我可以在单线程 C# 控制台应用程序中安全地使用 async void 异步处理队列中的多个项目吗?

javascript - 无法访问 for 循环中使用的链式 promise 内的外部作用域变量

javascript - 如何使此代码中不需要的字段?

javascript - Bootstrap popovers 可以不被销毁吗?

javascript - 添加 Web 表定位器中所有值的总和,仅前两个定位器的方法结果值

javascript - 使用固定 ip 从本地主机响应 native 获取

ios - 使异步 alamofire 请求同步

c# - UWP 从异步工作线程更新 UI