Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Puppeteer: multiple screenshots in one browser instance

so I want to screenshot a specific class multiple times, but all the time it would say Session Closed or Terminated, therefore I worked around implementing multiple screenshots opening multiple instances.

Could someone at least guide how to multiple instances on the same browser instance?

my code:

const puppeteer = require("puppeteer");

const SELECTOR = ".octicon";

(async () => {
  let screenshotNumber = 0;
  async function screenshots() {
    const browser = await puppeteer.launch({
      headless: true
    });

    try {
      let page = await browser.newPage();
      page.setViewport({ width: 1000, height: 600, deviceScaleFactor: 2 });

      await page.goto("https://github.com/");
      await page.waitForNavigation({ waitUntil: "networkidle" });

      const rect = await page.evaluate(selector => {
        const element = document.querySelector(selector);
        const { x, y, width, height } = element.getBoundingClientRect();
        return { left: x, top: y, width, height, id: element.id };
      }, SELECTOR);

      await page.screenshot({
        path: `octicon-${screenshotNumber}.jpg`,
        clip: {
          x: rect.left,
          y: rect.top,
          width: rect.width,
          height: rect.height
        }
      });

      browser.close();
      screenshotNumber++;
    } catch (e) {
      console.log(e);
      browser.close();
    }
  }

  async function run() {
    await screenshots();
    setTimeout(run, 200);
  }

  run();
})();
like image 521
Tomas Eglinskas Avatar asked Nov 08 '22 17:11

Tomas Eglinskas


1 Answers

Just running two screenshot commands consecutively without calling browser.close() works fine:

  await page.screenshot({
    path: `octicon-${screenshotNumber}.jpg`,
    clip: {
      x: rect.left,
      y: rect.top,
      width: rect.width,
      height: rect.height
    }
  });

  screenshotNumber++;

  await page.screenshot({
    path: `octicon-${screenshotNumber}.jpg`,
    clip: {
      x: rect.left,
      y: rect.top,
      width: rect.width,
      height: rect.height
    }
  });

  browser.close();
like image 127
Vaviloff Avatar answered Nov 15 '22 11:11

Vaviloff