Jack Caycedo
Jack Caycedo

Reputation: 21

Puppeteer - Using only 1 browser instance

How do I have it so when doing multiple task of puppeteer it only uses 1 browser instance? The site I am scraping rn is detecting the creation of browser instances even after await browser.close(). So if I always have the browser open I can get around it.

Example Scenario:


(async() => {
    const browser = await puppeteer.launch({headless: true}); //

    // Have this only run once ^^^^

    // Command gets run, it should not make a new browser and instead go
    // to make a new page    
    // VVVVVVVV

    const page = await browser.newPage();
    
    await page.goto(args[1]) // Go to the url the user specified

    // do some stuff

    await page.close();

   //repeat from browser.newPage();

})();

Any ideas?

Upvotes: 1

Views: 4971

Answers (2)

Md. Abu Taher
Md. Abu Taher

Reputation: 18826

In addition to the puppeteer.connect() mentioned in another answer, here is another one.

A very easy way to do this is to create the browser only once. Initialize it only if it was not initialized before. Just ensure the browser variable is outside of whatever scope you have, if it's an express app, ensure it's outside of the route.

let browser;

(async() => {
    if(!browser) browser = await puppeteer.launch({headless: true});

    const page = await browser.newPage();
    
    await page.goto(args[1]) // Go to the url the user specified

    // do some stuff

    await page.close();

})();

Upvotes: 7

vsemozhebuty
vsemozhebuty

Reputation: 13782

You can launch the browser once and then use puppeteer.connect().

chrome.exe --remote-debugging-port=9222
(async() => {
    const browser = await puppeteer.connect({
      browserURL: 'http://localhost:9222',
      defaultViewport: null,
      headless: true,
    });

    const page = await browser.newPage();

    await page.goto(args[1]) // Go to the url the user specified

    // do some stuff

    await page.close();

    browser.disconnect();
})();

Upvotes: 2

Related Questions