Automating With Puppeteer

Nov 2, 2018 · 284 words · 2 minute read puppeteer automation

Puppeteer is a node package that allows you to control Chrome over an API. Most things that you can do in a browser you can do in Puppeteer. All you need to do to install puppeteer is just run “npm i puppeteer.”

One note from the repo is that Puppeteer downloads the latest copy of Chromium, and that can be a large file. A word of warning when you install and deploy: I had some problems running this on server-less solutions.

My goal with Puppeteer was to try to make a custom testing take some screenshots and do some performance metrics. For this example, let’s try to build a script that will take screenshots at a number of different sizes.

For our app, let’s just take some screenshots of a page from some different viewpoints.

 (async () => {
      const browser = await puppeteer.launch({args: ['--no-sandbox', '--disable-setuid-sandbox']});
      const page = await browser.newPage();

      // An array of viewport sizes for different devices.
      const viewports = [1366, 1280, 1024, 640, 414, 411, 375, 320];

      await page.goto(myVar);

      for(let i=0; i < viewports.length; i++) {
        let vw = viewports[i];

        // Set only matters of fullpage: false 
        await page.setViewport({
          width: vw,
          height: 1000
        });

        await page.screenshot({
          path: `./screenshots/screen-${vw}.png`,
          fullPage: true
        });
      };
      browser.close();
    })();

Let’s walk through this script a little it. The Puppeteer is easy to control with a few sets of commands. You have to launch and then you can set options such as which page to go to how big that you want your viewport. Then when you are done with all your comments you can set the puppeteer to close.

To learn more and explore Puppeteer. Here are a few helpful links: