ScreenshotNeo

BlogHow-to

How to Screenshot a Specific HTML Element

Capture one DOM element with Chrome DevTools, Playwright, or Puppeteer. Learn how to choose a reliable target and handle common screenshot issues.

By the ScreenshotNeo team4 October 20269 min read

To screenshot a specific HTML element, use Chrome DevTools for a one-time manual capture, or use a browser automation library for repeatable captures. In Chrome, select the node in the Elements panel and choose Capture node screenshot. In Playwright, call locator.screenshot(); in Puppeteer, call ElementHandle.screenshot().

These methods target a DOM element. A normal operating-system screenshot shortcut captures pixels from the screen and does not identify or crop to a DOM node. A node or element screenshot is also different from a full-page screenshot: it captures the selected element’s visible box, not every element on the page.

Choose the right method

Method Best for How you choose the target
Chrome DevTools One-off capture while inspecting a page Select a node in the Elements panel
Playwright Tests, repeatable scripts, or batches Use a locator such as a role, test ID, or CSS selector
Puppeteer Automation in a project already using Puppeteer Find an element handle with a selector
ScreenshotNeo Capture through an HTTP API without managing browser setup Pass a page URL and a CSS selector

Choose based on whether you need a manual image or a repeatable workflow, and on which automation framework your project already uses. A full-page capture includes the scrollable page; an element capture is scoped to one target.

1. Capture a node in Chrome DevTools

  1. Open the webpage in Chrome.
  2. Open DevTools and select the Elements panel.
  3. Use the element picker or inspect the DOM tree to select the exact node.
  4. Right-click the selected node and choose Capture node screenshot. You can also open the DevTools Command Menu and search for that command.
  5. Find the downloaded image in your downloads folder.

Chrome’s documentation says, “You can screenshot any individual node in the DOM Tree.” See Chrome DevTools documentation for DevTools guidance.

This is the simplest route when you only need one image and can inspect the page by hand. If the image is wrong, verify that the intended node itself—not a neighboring wrapper or child—is selected.

2. Capture an element with Playwright

Playwright’s locator API is useful when you need the same capture repeatedly, such as in a script or a test. Locators retry and auto-wait, and can target elements by role, text, label, test ID, or CSS. Prefer a semantic locator or a stable test ID where practical; positional selectors and broad selectors are more likely to match the wrong element as a page changes.

Runnable JavaScript example

Install Playwright and its Chromium browser, then save this as element-shot.mjs and run it with Node.js:

npm install playwright
npx playwright install chromium
import { chromium } from 'playwright';

const browser = await chromium.launch({ headless: true });
try {
  const page = await browser.newPage({ viewport: { width: 1280, height: 900 } });
  await page.goto('https://example.com', { waitUntil: 'domcontentloaded' });

  const card = page.locator('main article').first();
  await card.waitFor({ state: 'visible' });
  await card.screenshot({ path: 'element.png' });
} finally {
  await browser.close();
}

Replace https://example.com and main article with your page and target selector. The .first() call intentionally picks the first match; remove it if the locator should identify exactly one element, or assert uniqueness in your test. For example, Playwright Test users can use an expectation that the locator has count one before capturing.

Useful Playwright variations

  • Accessible role: page.getByRole('heading', { name: 'Pricing' })
  • Stable test ID: page.getByTestId('summary-card')
  • CSS selector: page.locator('.summary-card')
  • Image bytes instead of a file: omit path and store or attach the returned buffer.

The locator screenshot API accepts screenshot options. Set the output path to select the filename and extension, and consult the Playwright locator screenshot documentation for the current options supported by your installed version. Use page.screenshot({ fullPage: true }) only when the intended result is the whole page rather than the chosen element.

3. Capture an element with Puppeteer

Puppeteer exposes screenshot capture on an element handle. The following complete Node.js script launches Chromium, navigates to a page, waits for a matching element, saves its screenshot, and closes the browser even if capture fails.

npm install puppeteer
import puppeteer from 'puppeteer';

const browser = await puppeteer.launch({ headless: true });
try {
  const page = await browser.newPage();
  await page.setViewport({ width: 1280, height: 900 });
  await page.goto('https://example.com', { waitUntil: 'domcontentloaded' });

  const element = await page.waitForSelector('main article', { visible: true });
  if (!element) throw new Error('Target element was not found');
  await element.screenshot({ path: 'element.png' });
} finally {
  await browser.close();
}

Change the URL and selector to match your page. Puppeteer’s element screenshot method scrolls the element into view if needed; that does not mean arbitrary hidden content is made visible. See the Puppeteer screenshot guide and ElementHandle screenshot API.

4. Use Playwright from the command line

If your environment has the Playwright CLI installed and a page open in its session, its screenshot command can target a specific element. The CLI supports an optional target and filename; format can be inferred from the extension or set with a type option. CLI commands can change between packages and versions, so check the installed CLI’s help for its exact command syntax.

playwright-cli screenshot --help

The official Playwright CLI screenshot reference documents target screenshots, output filenames, PNG/JPEG/WebP, full-page capture, and a high-resolution option. High-resolution capture uses device pixels; mouse coordinates are expressed in CSS pixels, so coordinates may not map one-to-one at that scale.

What an element screenshot includes

Element screenshots are rendered captures, not exports of an element’s HTML or CSS. Their dimensions and contents depend on the element’s layout and what is visibly rendered at capture time.

  • Element bounds: the capture is clipped to the element’s size and position.
  • Scrolled elements: a scrollable container generally contributes its currently visible, scrolled content, not all of its overflow.
  • Overlays: content covered by another element remains covered in the rendered screenshot.
  • Lazy content: images or other content that has not loaded may appear blank or incomplete. Wait for the content you need before capturing.
  • Hidden elements: scrolling into view is not equivalent to revealing an element hidden with CSS or absent from the rendered page.
  • Detached elements: if a framework replaces or removes a node during capture, the operation can fail. Locate it again after the page reaches its final state.

For Playwright, the element-handle screenshot documentation describes actionability checks and scrolling into view; it also says a detached element causes an error. See Playwright ElementHandle screenshot.

Make captures consistent

  1. Use a stable target. Prefer a test ID or semantic locator where available. Confirm that the selector resolves to the intended single element.
  2. Set the viewport. Responsive layout can change the target’s size, wrapping, and position. Use the same viewport for repeat runs.
  3. Wait for the right state. Wait for the target to be visible and for any required text, image, or application state to appear. A fixed delay can help with a known transition, but is less reliable than waiting for a selector or condition.
  4. Control changing content. Animations, clocks, rotating banners, randomized data, and live content can make images differ between runs. Where a stable baseline matters, use a consistent browser environment and page state.
  5. Account for device scale. Device pixel ratio affects raster dimensions. Keep the browser context and device settings consistent when comparing captures.
  6. Capture after scrolling is settled. Automation may scroll the target into view. Sticky headers or scroll-triggered content can change the appearance during that movement.

For visual regression tests, rendering can vary with the operating system, browser version, settings, hardware, and headless mode. Playwright recommends generating and comparing screenshots in a consistent environment; see its visual comparisons guide.

Troubleshooting

Symptom Likely cause Fix
No element found or a timeout The selector is wrong, the page has not rendered it, or it is inside a frame. Inspect the live DOM, wait for the application state, and use the appropriate frame locator or frame context.
The wrong element was captured A broad selector matches several nodes, or a positional match changed. Use a more specific locator, assert the match count, or identify the element by role, accessible name, or test ID.
Screenshot call fails because the node detached The page re-rendered or replaced the element between lookup and capture. Wait for the final state and reacquire the locator or element handle immediately before capture.
Image is empty or incomplete The target is hidden, content is lazy-loaded, or the page has not reached the required state. Wait for visibility and the relevant content; scroll the page or container as needed. Explicitly reveal content only when that is part of the intended state.
Part of the target is missing The target is clipped by a scrollable container, has overflow, or is covered by another element. Check its computed layout and stacking context. Scroll the container to the intended position; capture a different wrapper only if the whole region is intended.
Image looks different from the browser Viewport, device scale, fonts, browser version, or page state differs. Use the same viewport and browser environment, wait for fonts and content, and remove or control animations and changing data where appropriate.
Browser does not start in automation The browser package or its required browser installation is missing, or the runtime lacks required system dependencies. Install the browser using the framework’s documented installation command and follow its environment-specific setup instructions.
Output format is unexpected The filename extension or screenshot option does not match the desired format. Specify a filename with the desired supported extension and verify the installed framework’s screenshot options.

Performance, reliability, and cost

For one manual capture, DevTools avoids writing or maintaining a script. For repeated captures, browser automation adds browser startup and page-loading work, so reuse a browser process for a batch rather than launching one per element. Close pages and browsers when finished, and avoid capturing more often than the workflow needs.

Reliability depends chiefly on selecting the right node and capturing it in a stable state. Waiting for a meaningful condition is usually more dependable than choosing an arbitrary sleep duration. Network-idle conditions can be unsuitable for pages with continuous background requests; wait for the target content instead.

Playwright and Puppeteer are software libraries; their documentation does not state a per-screenshot fee. Your costs may come from the machine or CI environment that runs the browser. A screenshot service can avoid managing browser setup, with pricing and billing behavior determined by that service.

Or skip the browser setup

ScreenshotNeo is a website screenshot API and MCP server from ScreenshotNeo. It can capture one element by CSS selector. For element capture, pass the page URL and the selector option supported by the API; see the ScreenshotNeo API documentation for the current parameter names and options.

curl -G "https://api.screenshotneo.com/v1/shot" \
  -d access_key=YOUR_API_KEY \
  --data-urlencode url=https://example.com \
  --data-urlencode selector='.summary-card' \
  -o element.webp
import requests

r = requests.get(
    "https://api.screenshotneo.com/v1/shot",
    params={
        "access_key": "YOUR_API_KEY",
        "url": "https://example.com",
        "selector": ".summary-card",
    },
    timeout=90,
)
r.raise_for_status()
open("element.webp", "wb").write(r.content)
const q = new URLSearchParams({
  access_key: 'YOUR_API_KEY',
  url: 'https://example.com',
  selector: '.summary-card',
});
const res = await fetch(`https://api.screenshotneo.com/v1/shot?${q}`);
if (!res.ok) throw new Error(`Screenshot request failed: ${res.status}`);
const image = Buffer.from(await res.arrayBuffer());
await import('node:fs/promises').then(({ writeFile }) => writeFile('element.webp', image));

Cookie banners, newsletter popups, and chat widgets are removed before the shot. Bot checks, blank pages, and failed loads are never billed, and response headers report the page verdict and billing status. An MCP server lets AI agents take screenshots. The free plan includes 1,000 screenshots a month with no card; paid plans start at $5 for 3,000.

Sign up free for 1,000 screenshots a month, with no card required.

FAQ

Can I screenshot an element that is offscreen?

Automation screenshot methods can scroll a target into view. Check the resulting image when sticky or scroll-triggered page elements may affect it.

Can I capture every item in a list?

Yes. Iterate over a set of matching locators or handles and save each result with a distinct filename. Make sure the locator collection represents the items you intend to capture.

Does an element screenshot include the element’s shadow?

It captures rendered pixels within the element’s bounds. Whether a visual effect extends beyond those bounds depends on clipping and layout; inspect the output if shadows or overflow matter.

Can I get the element as HTML instead of an image?

No. Screenshot methods produce rendered image output. Use DOM inspection or serialization when you need markup rather than pixels.

References