2

我正在使用 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可以做到这一点吗?

4

2 回答 2

3

您可能想查看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();
})();
于 2020-06-02T20:13:03.590 回答
2

是的,这是默认的异步行为。您只需要打开 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
})();
于 2020-06-02T18:49:14.600 回答