Everything you need to know about taking screenshot of a website using Playwright

Post by
Andrew Pierno
Everything you need to know about taking screenshot of a website using Playwright

In this tutorial, we will learn how to take a screenshot of a website using Playwright. We’ll use Playwright’s screenshot method to generate screenshot of a website using just the website url as input. We’ll also dive deep into some of the options provided by screenshot method and discover some frequently used use cases.

Installing Playwright

Using yarn

yarn add playwright

Using npm

npm install playwright

Taking a Screenshot

Once you’ve got Playwright installed, we’ll now write a function that accepts website url as a parameter and saves it to a specified path locally for now.

const { chromium } = require("playwright");
const takeScreenshot = async (websiteUrl) => {
  const browser = await chromium.launch();
  const context = await browser.newContext();
  const page = await context.newPage();
  await page.goto(websiteUrl);
  await page.screenshot({ path: "my_screenshot.png" });
  await browser.close();
};

This code will launch a Chromium browser, navigate to the websiteUrl passed to the function, take a screenshot of the page, and save it locally to a file named example.png.

Screenshot Options

The screenshot method accepts options typed under the PageScreenshotOptions interface to use while taking screenshots:

  • animations - stops CSS animations, CSS transitions, and Web Animations when set to "disabled". Defaults to "allow".
  • caret - hides text caret when set to "hide", otherwise behavior is not changed. Defaults to "hide".
  • clip - an object specifying the clipping of the resulting image.
  • fullPage - takes a screenshot of the full scrollable page when set to true. Defaults to false.
  • mask - specifies locators that should be masked when the screenshot is taken.
  • omitBackground - allows capturing screenshots with transparency and hides the default white background. Not applicable to jpeg images. Defaults to false.
  • path - the file path to save the image to. The screenshot type will be inferred from the file extension.
  • quality - the quality of the image, between 0-100. Not applicable to png images.
  • scale - sets the scale of the screenshot image.
  • timeout - sets the maximum time in milliseconds. Defaults to 30 seconds.
  • type - specifies the screenshot type. Defaults to png. Can be jpeg or png

Let’s try implementing some of the most frequently used cases:

Taking screenshot of the entire page

Just pass the fullPage option as true (which defaults to false) and you’re good.

const { chromium } = require("playwright");
const takeFullPageScreenshot = async (websiteUrl) => {
  const browser = await chromium.launch();
  const context = await browser.newContext();
  const page = await context.newPage();
  await page.goto(websiteUrl);
  await page.screenshot({ path: "my_screenshot.png", fullPage: true });
  await browser.close();
};

Taking screenshot of a specific area or region

Easy, just use the clip option to define the image’s clipping. It’s an object with the following properties:

  • x: the x-coordinate of the top-left corner of the clipping area
  • y: the y-coordinate of the top-left corner of the clipping area
  • width: the width of the clipping area
  • height: the height of the clipping area
const { chromium } = require("playwright");
const takeAreaScreenshot = async (websiteUrl) => {
  const browser = await chromium.launch();
  const context = await browser.newContext();
  const page = await context.newPage();
  await page.goto(websiteUrl);
  await page.screenshot({
    path: "my_screenshot.png",
    clip: {
      x: 0,
      y: 0,
      width: 100,
      height: 100
    },
  });
  await browser.close();
};

Taking screenshot of a specific element

Clipping won’t make sense always, if you can grab an element using query selectors, always a better idea to use this method.

const { chromium } = require("playwright");
const takeElementScreenshot = async (websiteUrl) => {
  const browser = await chromium.launch();
  const context = await browser.newContext();
  const page = await context.newPage();
  await page.goto(websiteUrl);
  const element = await page.locator('.element_selectors_here');
  await element.screenshot({ path: "my_screenshot.png" });
  await browser.close();
};

Taking a screenshot and uploading it to S3

S3 is undoubtedly one of the most widely used file storage services out there.

Make sure to install the AWS sdk before we begin.

Using yarn

yarn add aws-sdk

Using npm

npm install aws-sdk

Next, let’s write a function to take a screenshot and upload it to S3. The function will accept websiteUrl, bucketName and fileName as input and return uploadedFileUri as output.

const { chromium } = require("playwright");
const AWS = require("aws-sdk");
AWS.config.update({
accessKeyId: 'YOUR_ACCESS_KEY',
secretAccessKey: 'YOUR_SECRET_KEY',
region: 'YOUR_REGION',
});
const s3 = new AWS.S3();
const takeScreenshotAndUpload = async (websiteUrl, bucketName, fileName) => {
const browser = await chromium.launch();
const context = await browser.newContext();
const page = await context.newPage();
await page.goto(websiteUrl);
const screenshot = await page.screenshot();
const params = {
Bucket: bucketName,
Key: fileName,
Body: screenshot,
};
const uploadedFile = await s3.upload(params).promise();
await browser.close();
return uploadedFile;
};

Generating PDF of a website

If you’re looking to generate a PDF instead, use the pdf method provided by Playwright.

const { chromium } = require("playwright");
const takeElementScreenshot = async (websiteUrl) => {
const browser = await chromium.launch();
const context = await browser.newContext();
const page = await context.newPage();
await page.goto(websiteUrl);
await page.pdf({ path: "mypdf.pdf" });
await browser.close();
};

Reliably taking screenshots of websites at scale

While it is super quick to write a function to take screenshots using playwright, unfortunately, it gets very complicated very quickly as you try to scale it given the resource intensive behaviour of any headless browser. Managing proxies, handling cookies, storing and caching images is something we haven’t even talked about.

Screenshotapi.net solves the above problems with grace. Screenshotapi provides a reliable API to take screenshots or generate pdfs of a website at blazing fast speeds. Screenshotapi process a few million screenshots every month without fail. Screenshotapi is trusted by marquee companies like the crypto.com, dentsu, e.ventures to name a few.

screenshot api customers

Hope the tutorial was helpful. Don’t forget to give screenshotapi.net a shot, we have a 7-day free trial that allows you to capture up to 100 screenshots.

©2024 ScreenshotAPI. All Rights Reserved.