In This Article

Back to blog

Taking Screenshots With Playwright: A Beginner’s Guide

Tutorials

Learn to take a screenshot with a Playwright headless browser in Node.js, using full-page screenshots or capturing specific elements of a web page.

Marijus Narbutas

Last updated - ‐ 6 min read

Key Takeaways

  • Playwright's screenshot functionality is among the best compared to similar tools.

  • Playwright can be installed with an npm command, and page screenshots can be captured using page.screenshot(options) method.

  • In some cases, it might be better to make element screenshots or use snapshots instead of page screenshots.

Playwright is a versatile web automation tool widely used for web scraping dynamic websites. Another useful feature of Playwright is the ease of performing additional data collection tasks, such as taking a screenshot. Playwright screenshot methods can aid or even replace many more complicated web scraping approaches.

Why Use Playwright for Screenshots?

Unlike tools like Selenium that send HTTP requests to a headless browser driver, Playwright connects directly to the browser’s WebSocket, allowing it to capture the web page rendering process in real-time. As such, you can take a screenshot when the website is fully loaded and stable to avoid flakiness.

Puppeteer also has a similar architecture, so it can work quickly and with high accuracy. However, Playwright offers multi-browser support (WebKit, Firefox, Chromium) and more convenient auto-wait mechanisms that Puppeteer lacks.

While no tool handles dynamic, highly protected websites perfectly, Playwright’s screenshot features require less setup.

The points here are crucial only if your main use case of a headless browser is visual regression testing or some web scraping applications that require screenshots. The comparison between Selenium, Playwright, and Puppeteer is more complicated than taking a page screenshot, so consider them all in other cases.

Setting Up Playwright

Playwright is available as an npm package and can be installed in any Node.js project. Start by installing the newest version of Node.js , then open Command Prompt (Windows) or Terminal (Mac/Linux) to verify it with these commands:

node -v
npm -v

This will check the validity of Node.js and Node Package Manager (npm) installation. If no errors are returned and you can see the version numbers, proceed to create your project folder and navigate to it:

mkdir screenshot-bot
cd screenshot-bot

Then, we need to initialize the Node.js project:

npm init -y

Finally, we can install Playwright with an npm command:

npm install playwright

After Playwright is installed, you can create a JavaScript code file, such as screenshots.js, in your project folder and edit it with a code editor. We recommend using VS Code but any code editor that supports JavaScript will do. Now we can start writing the code for taking a page screenshot with Playwright.

Before you can actually run a browser, however, you’ll need to download it. Run the following command in the Terminal if it’s your first time using Playwright:

npx playwright install

Doing so will download all browsers' binaries, which will be used by Playwright.

Ready to get started?
Register now

Full Page Screenshot Example

A full-page screenshot with Playwright captures the entire height of a webpage. The screenshot method page.screenshot(options) includes the object options configuration parameters path: for where the screenshot will be saved, and fullPage: true, which tells Playwright to capture the entire web page.

const { chromium } = require('playwright');

(async () => {
  const browser = await chromium.launch();
  const page = await browser.newPage();
  
  await page.goto('https://iproyal.com/');
  
  // Capture the entire page
  await page.screenshot({ 
    path: 'full-page.png',
    fullPage: true 
  });
  
  await browser.close();
})();

For large-scale projects, you will also need to implement Playwright proxies , bypass CAPTCHAs, and other anti-scraping measures. We'll skip these parts for simplicity's sake, but be sure to check our blog for further advice.

It should also be noted that the path: 'full-page.png' includes the page name with the .png extension, which automatically saves it as such. Getting page screenshots in .jpg, for example, requires an additional quality parameter (1-100, where 100 is the highest quality).

await page.screenshot({ 
  path: 'screenshot.jpg',
  fullPage: true,
  quality: 80  // 80% quality
});

This works well for a full-page screenshot of static web pages, but if you need a full scrollable page screenshot, you'll need a different approach. Sites like Twitter or Reddit use infinite scroll, which will result in blank spaces while the website is still loading elements.

The solution is to scroll to the bottom with a delay so that the page loads before you take a screenshot. Here's how the addition might look:

// Function to scroll to bottom with delays
await page.evaluate(async () => {
  const delay = 100; // delay in ms
  for (let i = 0; i < document.body.scrollHeight; i += 100) {
    window.scrollTo(0, i);
    await new Promise(resolve => setTimeout(resolve, delay));
  }
});

// Taking the full page screenshot
await page.screenshot({ path: 'infinite-scroll.png', fullPage: true });

Modern web pages often have multiple scrollable elements that you might want to capture. It’s better to locate and capture just those elements separately than attempting to grab them in one go.

Capturing a Specific Element

Building on how we captured the full page screenshot, you can get element screenshots (like a button, card, or section) with page.locator().screenshot() method. It uses a selector to find an element and then takes its screenshot without capturing the full page. Here's how the code might look:

await page.locator('#hero-header-block').screenshot({ 
  path: 'hero-header-block.jpg',
  quality: 85     
});

In our case, we used the CSS ID #hero-header-block to select the first part of the IProyal home page. To take a different element screenshot, you'll need to inspect the element with DevTools by right-clicking and choosing Inspect on a browser like Google Chrome.

Another option is to use Playwright's built-in page inspector tool. It opens in a separate window and allows you to click on elements directly to generate their selector code. Use the following command to run it:

npx playwright codegen https://iproyal.com

If there are two or more elements with the same locator, Playwright will not take a screenshot and might return an error. That's why it's useful to get to know multiple ways to use CSS selectors.

// By class name
await page.locator('.button').screenshot({ path: 'button.png' });

// By ID
await page.locator('#main-content').screenshot({ path: 'content.png' });

// By element type
await page.locator('h1').screenshot({ path: 'heading.png' });

// By attribute
await page.locator('[data-testid="card"]').screenshot({ path: 'card.png' });

// Nested selector (combining multiple selectors)
await page.locator('.container .item').screenshot({ path: 'item.png' });

// Combining class and element
await page.locator('button.primary').screenshot({ path: 'primary-btn.png' });

In some cases, it might be better to use more complex XPath expressions that can target some elements more specifically. Here's how it might look with page.locator().screenshot() method.

// By text content
await page.locator("xpath=//button[contains(text(), 'Click Me')]").screenshot({ path: 'button.png' });

// By attribute value
await page.locator("xpath=//div[@class='card']").screenshot({ path: 'card.png' });

// By position (first element)
await page.locator("xpath=(//div[@class='item'])[1]").screenshot({ path: 'first-item.png' });

// By multiple conditions
await page.locator("xpath=//button[@type='submit' and @class='primary']").screenshot({ path: 'submit-btn.png' });

Screenshots in Playwright Reports

Playwright can be configured to automatically capture and attach page screenshots when a test is executed ('on') or fails ('only-on-failure'). The easiest way is to modify your playwright.config.js file by adding the following:

module.exports = {
  use: {
    // Options: 'on', 'off', 'only-on-failure'
    screenshot: 'only-on-failure',
  },
};

To view the page screenshots, enter the following command and run the report viewer:

npx playwright show-report

Snapshot Testing vs Screenshots

For use cases like visual regression testing, it might be better to use snapshots instead of page screenshots. A snapshot is a captured representation of the structure and state of an element at a specific moment in time, which may or may not include a page or element screenshot.

  • Visual snapshots capture an actual pixel-by-pixel image, page, or element, which can be compared against future snapshots in test runs.
  • ARIA snapshots capture text-based representations of the accessibility tree, describing roles, hierarchy, and attributes.

Page screenshots are more useful for documentation, debugging, reports, or, especially, when paired with AI tools for transcribing and various web scraping tasks. If your use case has more to do with testing, visual, or ARIA snapshots might be better suited.

Conclusion

Playwright's screenshot functionalities are powerful enough for most common use cases, so it's helpful to learn how to use them. We covered some of the basics of how to take partial or full-page screenshots. Expert knowledge of capturing real websites will come with practice.

Create Account
Share on
Article by IPRoyal
Meet our writers
Data News in Your Inbox

No spam whatsoever, just pure data gathering news, trending topics and useful links. Unsubscribe anytime.

No spam. Unsubscribe anytime.

Related articles