How to Screenshot Specific Elements with Playwright

2/22/2025

Hey there! Laura and Heidi here from SCRNIFY. Today, we're diving into one of the most useful features of Playwright: taking screenshots of specific elements on a webpage. If you've ever found yourself overwhelmed by the amount of information in a full-page screenshot or searching for a needle in a haystack when trying to capture a specific part of a page, this guide is for you! And if you’re interested in similar techniques for Puppeteer, check out our previous article on How to Screenshot Specific Elements with Puppeteer.

Capturing screenshots of particular elements can be an essential tool in web testing and documentation. Rather than presenting your team with a cluttered image of an entire page, you can highlight only what’s necessary. This not only makes bug reporting clearer but also improves visual consistency in documented processes.

Let’s explore how to leverage Playwright’s element-handling abilities for targeted screenshots!

Understanding Element Screenshots in Playwright

Before we jump into the code, it’s important to grasp how Playwright allows us to interact with elements on a page. At its core, Playwright gives us methods to select and manipulate elements and take screenshots directly of those elements.

There are a couple of ways to achieve this:

  1. By using the elementHandle.screenshot() method.
  2. By leveraging locators with page.locator().screenshot().

Both methods are powerful, allowing you to focus on exactly what you need from a webpage.

Capturing Screenshots of Specific Elements

Method 1: Using elementHandle.screenshot()

The direct approach to capturing an element's screenshot is by obtaining its "handle." The handle refers to an object that allows you to interact with that specific element. Here’s how to do it:

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

async function takeElementScreenshot() {
    const browser = await chromium.launch();
    const page = await browser.newPage();

    try {
        await page.goto('https://example.com');

        // 1. Find the element you want to screenshot (e.g., the main heading)
        const elementHandle = await page.$('h1');  // Change the selector as necessary

        if (elementHandle) {
            // 2. Take a screenshot of the element
            await elementHandle.screenshot({ path: 'heading-element.png' });
            console.log('Screenshot of the heading element saved!');
        } else {
            console.log('Element not found.');
        }

    } finally {
        await browser.close();
    }
}

takeElementScreenshot().catch(console.error);

Explanation of the Code:

  1. Launch Browser: We initiate a Chromium browser instance using chromium.launch().
  2. Navigate to URL: We then navigate to a webpage using page.goto().
  3. Select Element: The page.$('h1') method grabs the specific <h1> element (or any desired selector). This returns an ElementHandle.
  4. Screenshot: The key operation elementHandle.screenshot({ path: 'heading-element.png' }) captures the screenshot directly of the heading element, saving it to the desired path.

Method 2: Using Playwright Locators for Screenshots

Playwright locators, which allow us to select elements based on more complex criteria, are another powerful method for snapping screenshots. Here’s how you do it:

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

async function screenshotUsingLocator() {
    const browser = await chromium.launch();
    const page = await browser.newPage();

    try {
        await page.goto('https://example.com');

        // 1. Use page.locator() to find the element (e.g., the heading)
        const headingLocator = page.locator('h1');  // Change the selector as necessary

        // 2. Take a screenshot of the locator
        await headingLocator.screenshot({ path: 'heading-locator.png' });
        console.log('Screenshot of the heading element (using locator) saved!');

    } finally {
        await browser.close();
    }
}

screenshotUsingLocator().catch(console.error);

Key Takeaways:

  • The page.locator('h1') function dynamically uses Playwright locators to refer to the targeted <h1> element, allowing better flexibility in terms of element selection.
  • Calling headingLocator.screenshot(...) allows us to take a screenshot directly through the locator API.

Method of Clipping with page.screenshot()

If you prefer an alternative method, you can take a full-page screenshot and then clip it down to the specific element's bounding box as shown below:

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

async function captureAndClip() {
    const browser = await chromium.launch();
    const page = await browser.newPage();

    try {
        await page.goto('https://example.com');

        // 1. Get the bounding box of the element
        const elementBoundingBox = await page.evaluate(() => {
            const el = document.querySelector('h1');
            const { x, y, width, height } = el.getBoundingClientRect();
            return { x, y, width, height };
        });

        if (elementBoundingBox) {
            // 2. Use the clip option in page.screenshot()
            await page.screenshot({
                path: 'heading-clip.png',
                clip: elementBoundingBox
            });
            console.log('Clip of the heading element saved!');
        } else {
            console.log('Element not found.');
        }

    } finally {
        await browser.close();
    }
}

captureAndClip().catch(console.error);

How Clipping Works:

  1. Bounding Box: The code retrieves the bounding box using getBoundingClientRect(), which returns the size and position of the element.
  2. Clipping: The screenshot method then employs the clip option to restrict the screenshot to only the defined bounding box of the element.

Practical Considerations

While capturing element screenshots, consider the following best practices:

  • Ensure Element Visibility: Always wait for the element to be visible before taking the screenshot. Use page.waitForSelector() or the locator’s waitFor() method to guarantee the element is loaded.
  • Handle Scroll Positioning: If your element is outside the current viewport, scroll to the element using elementHandle.scrollIntoViewIfNeeded() before screenshotting.
  • Use Options Wisely: Remember to explore the options available with the screenshot methods, like omitBackground for transparency or specifying formats.

Conclusion

Congratulations! You've reached the end of this guide on taking element-specific screenshots with Playwright. By mastering these methods, you’ll be able to create sharp, focused images that can significantly enhance your web testing, documentation, and reporting workflows.

Whether you opt for the straightforward elementHandle.screenshot(), leverage the power of page.locator().screenshot(), or make use of clipping techniques, you have the tools you need to capture the right images every time.

If you're looking for a streamlined way to manage complex screenshot needs without the hassle, don't forget to check out SCRNIFY. We focus on taking the difficulty out of web captures so you can concentrate on what truly matters—your projects.

Happy screenshotting!

Laura & Heidi 🇦🇹

P.S. Do you have additional questions or interesting use cases for element screenshots? We'd love to hear about them! Send us an email at support@scrnify.com.

Ready to Get Started?

Sign up now and start capturing stunning screenshots in minutes.

Sign Up Now