How to handle multiple browser instances in Puppeteer?

You can handle multiple browser instances in Puppeteer, a Node.js library, by launching several browser instances. This can be useful when you need to perform tasks in parallel, like opening different URLs or handling different user sessions.

Here is a basic example of how to launch multiple browser instances in Puppeteer:

const puppeteer = require('puppeteer');

async function run() {
    // Launch the first browser instance
    const browser1 = await puppeteer.launch();
    const page1 = await browser1.newPage();
    await page1.goto('https://www.example1.com');

    // Launch the second browser instance
    const browser2 = await puppeteer.launch();
    const page2 = await browser2.newPage();
    await page2.goto('https://www.example2.com');

    // Do not forget to close the browsers when you are done
    await browser1.close();
    await browser2.close();
}

run();

This code will launch two browser instances, each one going to a different URL.

Remember to always close the browsers when you are done to prevent memory leaks.

But if you want to use the same browser instance to open multiple pages, you can use the browser.newPage() method multiple times:

const puppeteer = require('puppeteer');

async function run() {
    // Launch the browser instance
    const browser = await puppeteer.launch();

    // Open the first page
    const page1 = await browser.newPage();
    await page1.goto('https://www.example1.com');

    // Open the second page
    const page2 = await browser.newPage();
    await page2.goto('https://www.example2.com');

    // Do not forget to close the browser when you are done
    await browser.close();
}

run();

This code will open two pages in the same browser instance. It might be faster than the first method because it avoids the overhead of launching a new browser for each page. But keep in mind that all the pages inside a browser share the same memory and CPU, so it might not scale well if you need to open a large number of pages.

Related Questions

Get Started Now

WebScraping.AI provides rotating proxies, Chromium rendering and built-in HTML parser for web scraping
Icon