Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

To screenshot one part of a website, identify its DOM element with a selector, wait for it to be ready, then capture that element—not the whole page. In Playwright, the direct pattern is page.locator('css=article.card').screenshot(). For a user-facing control, prefer a role, label, or text locator when it identifies the target reliably; use CSS when you need to target a visual component or a stable DOM attribute.

Choose the right target before writing a selector

A CSS selector is a query that identifies one or more elements in the page’s DOM. The screenshot method then captures the element that the selector resolves to. This differs from a page screenshot, which captures the viewport or, with full-page options, the document.

First inspect the page and decide exactly what should appear in the image. A product card, invoice, or article section is usually best captured as an element. A complete page or viewport calls for a page-level screenshot instead. If repeated components are present, identify a meaningful parent container so the selector does not accidentally match the wrong one.

Prefer locators that express the target’s meaning

Playwright recommends built-in locators such as role, label, text, alt text, title, and explicit test IDs. They describe the interface in terms closer to how a user or test identifies it. Playwright describes locators as “the central piece of Playwright’s auto-waiting and retry-ability.” If CSS or XPath is necessary, Playwright’s page.locator() accepts a selector describing how to find an element. See Playwright’s locator guidance.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
#1 Best Overall
Elebase USB to USB C Adapter for iPhone 18 Pro Max,USBC Car Charger Adapter
  • Read Before You Buy — No Video Output: These adapters support charging and USB 2.0 data transfer, but cannot transmit video signals. Except for standard USB webcams (which use USB data only), they are not compatible with HDMI/DisplayPort cables, video-capable USB-C hubs, or docking stations with video output.
  • Convert USB-A Ports to USB-C: Designed to connect USB-C earphones, cables, flash drives, card readers, and other USB-C accessories to standard USB-A ports. Plug-and-play with no drivers or software required.
  • Aluminum Alloy Housing: Built with a sturdy aluminum alloy shell that aids in heat dissipation and protects against daily wear and scratches. Designed to maintain a stable and secure connection.
  • Compact & Travel-Friendly: The ultra-compact design allows the adapter to stay plugged into your device without blocking adjacent ports or adding bulk, reducing wear and tear on your original USB ports.
  • 12-Month Warranty: Backed by a 12-month manufacturer warranty for peace of mind. Designed to meet strict quality control standards for reliable everyday performance.

Use CSS when the capture target is a visual component, such as article.card, or when a stable ID or test attribute is available. Avoid selectors tied to incidental layout or generated class names: a redesign can break them even if the intended visual content remains.

Write a CSS selector that stays understandable

Keep the selector as short and specific as the page allows. These patterns cover common capture targets:

Target Example When it helps
Unique ID #invoice Use when the ID is unique and stable.
Component class article.card Use when the class represents a deliberate component, not a generated implementation detail.
Stable attribute form[data-testid="checkout"] Use when the site provides an explicit automation contract.
Meaningful content attribute img[alt="Company logo"] Use when the attribute identifies the intended element.
Short descendant path main article.card Use to narrow a component to a meaningful page region.
Direct child path nav > ul > li Use when direct parent-child structure matters.

Playwright also documents CSS extensions such as button:visible, article:has-text("Results"), and section:has(.error). Its CSS locators pierce open Shadow DOM; closed shadow roots are not covered by that behavior. These are Playwright-specific capabilities rather than selectors guaranteed in every browser tool. See Playwright’s other locator strategies.

Capture an element with Playwright

Install Playwright and its browser in a Node.js project, then run this complete example. Replace the URL and selector with the page and target you need:

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
const { chromium } = require('playwright');

(async () => {
  const browser = await chromium.launch();
  const page = await browser.newPage({ viewport: { width: 1280, height: 900 } });

  try {
    await page.goto('https://example.com', { waitUntil: 'domcontentloaded' });
    const card = page.locator('css=article.card');
    await card.screenshot({
      path: 'card.png',
      animations: 'disabled'
    });
  } finally {
    await browser.close();
  }
})();

The css= prefix makes the selector engine explicit; a CSS selector can also be passed directly to page.locator(). The locator screenshot waits for actionability, scrolls the target into view, and captures the matched element. See the Playwright locator screenshot API.

Rank #2
Anker USB-C Hub, 5-in-1 USB Hub for Laptops, 4K HDMI Multiport Adapter
  • 5-in-1 USB-C Hub: Experience comprehensive connectivity featuring a Power Delivery input, two USB-A 2.0 ports, a USB-A 3.0 port, and an HDMI port. (Note: The USB-C power delivery input port is only for connecting an external wall charger to power your laptop and cannot power peripheral devices.)
  • 90W Pass-Through Charging: Achieve optimal charging with 90W pass-through power to your laptop, supported by a total input of 100W, with the hub reserving 10W for operational efficiency. (Note: Wall charger not included.)
  • Quick Data Transfers: Accelerate your productivity with rapid data transfers using a high-speed 5Gbps USB 3.0 port and two 480Mbps USB 2.0 ports.
  • 4K HDMI Display: Enhance your visual experience with a hub capable of delivering 4K resolution at 30Hz in both mirror and extend modes. Please note that this hub is compatible with MacBook (macOS 12 and newer), Windows 10 and 11, ChromeOS, and laptops equipped with DP Alt Mode and Power Delivery. Note: This device is not compatible with Linux.
  • What You Get: Anker USB-C Hub (5-in-1, 4K HDMI), welcome guide, 18-month warranty, and our friendly customer service.

Adapt the locator when a semantic locator is clearer

If the target is a button users recognize by name, a role locator is often less coupled to its markup:

const button = page.getByRole('button', { name: 'Download invoice' });
await button.screenshot({ path: 'download-button.png' });

Likewise, use a label locator for a labeled form control, or a test ID when the site deliberately exposes one. A locator that resolves to multiple matches is ambiguous for a single-element screenshot. Scope it to a container or refine it with a meaningful filter rather than silently relying on the first match.

Capture the page instead when the whole page is wanted

Use the page screenshot API for a viewport or full document. For example:

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
await page.screenshot({ path: 'page.png', fullPage: true });

Element screenshot options apply to the element method; full-page output belongs to the page screenshot workflow. Playwright’s screenshot options also include masking dynamic areas and choosing scale: 'css' when one output pixel per CSS pixel is preferred. See Playwright screenshot documentation.

Make captures repeatable on dynamic pages

Locator auto-waiting helps ensure an element can be acted on, but it cannot determine when every page-specific detail has reached the state you want to preserve. Client-rendered text, remote data, web fonts, lazy images, and animation can still change the pixels.

Rank #3
Sale
Anker USB C Hub, 7in1 Multi-Port USB Adapter, 4K@60Hz USBC to HDMI Splitter
  • Sleek 7-in-1 USB-C Hub: Features an HDMI port, two USB-A 3.0 ports, and a USB-C data port, each providing 5Gbps transfer speeds. It also includes a USB-C PD input port for charging up to 100W and dual SD and TF card slots, all in a compact design.
  • Flawless 4K@60Hz Video with HDMI: Delivers exceptional clarity and smoothness with its 4K@60Hz HDMI port, making it ideal for high-definition presentations and entertainment. (Note: Only the HDMI port supports video projection; the USB-C port is for data transfer only.)
  • Double Up on Efficiency: The two USB-A 3.0 ports and a USB-C port support a fast 5Gbps data rate, significantly boosting your transfer speeds and improving productivity.
  • Fast and Reliable 85W Charging: Offers high-capacity, speedy charging for laptops up to 85W, so you spend less time tethered to an outlet and more time being productive.
  • What You Get: Anker USB-C Hub (7-in-1), welcome guide, 18-month warranty, and our friendly customer service.
  • Wait for the content you need: wait for a meaningful selector or application-specific state before capturing, rather than adding an arbitrary long delay by default.
  • Disable animations: Playwright’s locator screenshot option animations: 'disabled' reduces motion-related variation.
  • Mask volatile areas: mask counters, timestamps, rotating promotions, or other changing regions when they are not part of the test or artifact.
  • Control output scale: use scale: 'css' in screenshot options when CSS-pixel-sized output is the desired comparison baseline.
  • Load lazy content deliberately: if the target or its images appear only after scrolling, wait for them to load before capture; a locator being actionable does not guarantee every image has finished loading.

Use the equivalent in Puppeteer or Selenium

Puppeteer

Puppeteer accepts CSS selectors by default. Wait for the element, then call its screenshot method:

const puppeteer = require('puppeteer');

(async () => {
  const browser = await puppeteer.launch();
  const page = await browser.newPage();

  try {
    await page.goto('https://example.com', { waitUntil: 'domcontentloaded' });
    const element = await page.waitForSelector('article.card');
    if (!element) throw new Error('Target article.card was not found');
    await element.screenshot({ path: 'card.png' });
  } finally {
    await browser.close();
  }
})();

For a whole page, use page.screenshot(), not an element handle. Puppeteer also provides locator APIs and other selector engines for text, accessibility, XPath, and Shadow DOM use cases. See Puppeteer screenshot guidance and the waitForSelector API.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Selenium

Selenium’s locator guidance recommends a unique, predictable ID when available and a well-written CSS selector otherwise; it notes that complex DOM traversals are harder to debug and maintain. XPath can express targets too, but Selenium describes its syntax as more complicated and difficult to debug. See Selenium locator guidance.

The exact screenshot call depends on the Selenium language binding and driver. Selenium does not define one universal element-screenshot workflow in the cited guidance, so pair the CSS locator with that binding’s element screenshot method. For example, in Python with Selenium 4:

from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC

options = webdriver.ChromeOptions()
driver = webdriver.Chrome(options=options)

try:
    driver.get("https://example.com")
    card = WebDriverWait(driver, 10).until(
        EC.visibility_of_element_located((By.CSS_SELECTOR, "article.card"))
    )
    card.screenshot("card.png")
finally:
    driver.quit()

Choose an approach for the capture you need

Need Recommended approach Reason
A user-visible control Playwright role, label, or text locator It identifies the target in terms a user perceives and is generally more resilient.
A stable automation contract data-testid or stable ID It avoids tying the selector to incidental layout.
A visual component Scoped CSS such as article.card It targets a component while keeping the selector readable.
A page or viewport Page screenshot API Element selection is unnecessary when the whole page is wanted.
Dynamic or animated content Locator screenshot with suitable waits, disabled animations, or masks It reduces layout and visual nondeterminism.

Troubleshoot selector screenshots

The selector finds no element

Check the exact markup and whether the element exists at the time the screenshot runs. A page may render it only after navigation, interaction, or an API response. Wait for the relevant state, verify the selector in the browser’s developer tools, and make sure the content is not inside a frame or a closed shadow root that your selector path cannot reach.

Rank #4
Sale
UGREEN USB to USB C Adapter Combo 4-Pack, 10Gbps USB C Converter Space Gray
  • Dual Converters, Infinite Potential:Includes 2× USB C male to USB A female adapters and 2× USB A male to USB C female adapters. Perfect for a wide range of uses—tablets with Bluetooth keyboards, expand USB ports on macbook, and more. Two different converters for all your daily needs
  • Next-Level 10Gbps & 3A Charging: No more slow 480Mbps, this usb to usb c adapter has a transfer speed of up to 10Gbps, allowing you to do more transferring in less time. This usb adapter fits both USB A and USB C charger, supporting up to 3A fast charging
  • Upgraded Exquisite Craftsmanship: With an aluminum alloy housing and metal connector, the usbc to usb adapter is extremely durable and sturdy. Rigorously tested to withstand more than 10,000 times of plugging and unplugging, ensuring long-lasting performance
  • Broad Compatible: The usb c to usb adapter widely supports all USB C/ USB A devices like laptops, tablets, cellphones, car chargers, and phone chargers. Such as compatible with MacBook Pro/Air 2023/2022, Thunderbolt 4/3 Devices,Apple MagSafe Watch 9/8/7/SE/Ultra, iPad Pro 2022/2021, Samsung Galaxy S23/S20/S10, and iPhone 17/16/15 Pro. Plug and play
  • Please Note: To reach 10Gbps speed, keep the cable under 3.3 ft. For USB A Male to USB C adapters, try flipping the USB C connector. USB C Male to USB A adapters support bidirectional 10Gbps transfer within 3.3 ft

The screenshot fails because more than one element matches

Scope the selector to a unique parent, use a more meaningful attribute, or filter by content when supported. Positional selection is appropriate only when the order itself is part of the page contract; otherwise a reordered list can produce a valid image of the wrong component.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

The element is found but the image is incomplete

Wait for the content or image load condition that matters to your page. Lazy images may require scrolling or a page-specific trigger. A visible element can still contain fonts or data that are loading, and animations can move the target during capture; use explicit waits, disabled animations, or masks as appropriate.

The selector breaks after a redesign

Replace generated classes, deep chains, or positional selectors with stable IDs, deliberate test IDs, or locators based on roles and labels when those accurately describe the target. A short selector is easier to inspect and repair than a long path through unrelated containers.

The screenshot captures the wrong scope

Confirm whether you need an element, viewport, or full document. Use the locator screenshot for a single component; use the page screenshot API for page output. If repeated components exist, narrow the locator to the intended section before capturing.

Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.Support on Ko-Fi

Or skip the browser setup

ScreenshotNeo is a website screenshot API and MCP server for developers. One GET request can return an image or PDF, and its element option accepts a CSS selector. Cookie banners and consent layers, newsletter popups, and chat widgets can be removed before capture; those cleanup steps can each be turned off. Bot checks, blank pages, timeouts, failed loads, and cache hits cost nothing, with response headers indicating the page verdict and whether the request was billed. Its MCP server gives AI agents tools including take_screenshot, get_page_info, and capture_pdf.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

For the full parameter reference, see the ScreenshotNeo documentation. This cURL request captures the selected CSS element:

Best Value
Anker USB C Hub, 5-in-1 USBC to HDMI Splitter with 4K Display
  • 5-in-1 Connectivity: Equipped with a 4K HDMI port, a 5 Gbps USB-C data port, two 5 Gbps USB-A ports, and a USB C 100W PD-IN port. Note: The USB C 100W PD-IN port supports only charging and does not support data transfer devices such as headphones or speakers.
  • Powerful Pass-Through Charging: Supports up to 85W pass-through charging so you can power up your laptop while you use the hub. Note: Pass-through charging requires a charger (not included). Note: To achieve full power for iPad, we recommend using a 45W wall charger.
  • Transfer Files in Seconds: Move files to and from your laptop at speeds of up to 5 Gbps via the USB-C and USB-A data ports. Note: The USB C 5Gbps Data port does not support video output.
  • HD Display: Connect to the HDMI port to stream or mirror content to an external monitor in resolutions of up to 4K@30Hz. Note: The USB-C ports do not support video output.
  • What You Get: Anker 332 USB-C Hub (5-in-1), welcome guide, our worry-free 18-month warranty, and friendly customer service.
curl -G "https://api.screenshotneo.com/v1/shot" 
  -d access_key=YOUR_API_KEY 
  --data-urlencode url=https://example.com 
  --data-urlencode selector=article.card 
  -o card.webp

Use your API key and the selector parameter shown above. ScreenshotNeo supports the parameter names used by other screenshot APIs as well, which can make switching easier. It also supports full-page capture with lazy images loaded, custom CSS and JavaScript, waiting for a selector or network idle, viewport and device settings, and other capture options; available features are included on every plan.

ScreenshotNeo offers 1,000 screenshots per month free with no card; paid plans start at $5 for 3,000 screenshots. Sign up for free and try ScreenshotNeo.

Frequently Asked Questions

Can CSS selectors target elements inside an iframe?

Not from the top-level document alone. Switch to or locate the frame in your automation tool, then query within that frame’s document.

Free tools Windows power users keep installed

One-click scans. No signup required.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Does a CSS selector screenshot include the element’s children?

Yes. Capturing a matched element captures its rendered box, including its descendant content, subject to the screenshot tool’s behavior and options.

Should I use XPath instead of CSS for an element screenshot?

Use the locator form that is clearest and most stable for your target. CSS is concise for common DOM structure and attributes; XPath can express other relationships, but Selenium cautions that complex XPath is harder to debug.

Product prices and availability are accurate as of the date/time indicated and are subject to change. Any price and availability information displayed on Amazon at the time of purchase will apply.