繁体   English   中英

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

[英]How to run scripts simultaneously with Puppeteer/Javascript?

我正在使用 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 和 memory 方面是相当昂贵的。 您可以使用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();
})();

是的,这是默认的异步行为。 您只需要打开 10 个选项卡并在这些页面上运行您的脚本。

这是示例:

(async () => {
    const browser = await puppeteer.launch({
        headless: false
    });
    const ids = ['1', '2', '3'];
    const pool = [];

    for (let index = 0; index < ids.length; index++) {
        pool.push(
            browser.newPage() // create new page for each id
                .then(page => {
                    const currentId = ids[index];
                    // your script over current page
                })
        );
    }

    await Promise.all(pool); // wait until all 10 pages finished
    await browser.close(); // close the browser
})();

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM