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

Use Pyppeteer’s ElementHandle.screenshot() method. Load the page, select the element with page.querySelector(), verify that a handle was returned, and call await element.screenshot({'path': 'element.png'}). Pyppeteer scrolls the element into view, measures its bounding box, and captures that rectangle.

How to screenshot one element with Pyppeteer

This complete example saves the first <h1> on example.com as a PNG:

import asyncio
from pyppeteer import launch

async def main():
    browser = await launch()
    page = await browser.newPage()
    await page.goto('https://example.com')

    element = await page.querySelector('h1')
    if element is None:
        raise RuntimeError('No element matched the selector')

    await element.screenshot({'path': 'h1.png'})
    await browser.close()

asyncio.get_event_loop().run_until_complete(main())

querySelector() returns an ElementHandle for the first matching node. The null check prevents a confusing failure later if the selector does not match anything. The element method then performs the scroll, bounding-box lookup, and clipped screenshot for you.

Install Pyppeteer and its browser

Pyppeteer is an unofficial Python port of Puppeteer for controlling Chrome or Chromium. Install it in the environment that will run your script:

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.
python3 -m pip install pyppeteer

On first use, Pyppeteer can download its bundled Chromium revision. To trigger that download before running your program, use:

pyppeteer-install

The project documentation says Pyppeteer works best with its bundled Chromium version. In a deployment, keep the package and browser runtime aligned rather than assuming that an arbitrary system Chrome binary will behave identically.

Screenshot a CSS selector after the page renders

Many pages build their content with JavaScript. Selecting immediately after goto() can therefore return no node, or can capture an element before its final layout. Wait for a selector when the page has a predictable DOM target:

import asyncio
from pyppeteer import launch

async def main():
    browser = await launch()
    page = await browser.newPage()
    await page.goto('https://example.com', {'waitUntil': 'networkidle2'})
    await page.waitForSelector('.product-card')

    card = await page.querySelector('.product-card')
    if card is None:
        raise RuntimeError('No .product-card element matched')

    await card.screenshot({
        'path': 'product-card.png',
        'type': 'png',
    })
    await browser.close()

asyncio.get_event_loop().run_until_complete(main())

Use a selector that identifies the exact node you want, such as #invoice-total, article h2, or [data-testid="chart"]. querySelector() chooses only the first match; if several elements are required, use page.querySelectorAll() and screenshot each handle.

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

What element.screenshot() actually captures

Automatic scrolling and clipping

Pyppeteer’s element screenshot implementation scrolls the node into view, obtains its bounding box, and sends a clipped capture to the page screenshot implementation. The clip uses the element’s x and y coordinates, width, and height.

The result is the element’s visible box, including the effects of its current layout, padding, borders, and transforms. Content outside that rectangle is not included. A scrollable element is captured at its current scroll position; the method does not promise a full image of all content hidden inside an overflow container.

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.

One element versus several matches

A CSS selector can match many nodes, but querySelector() returns only the first. For repeated cards, loop through all handles and give each output a distinct filename:

cards = await page.querySelectorAll('.card')
if not cards:
    raise RuntimeError('No cards found')

for index, card in enumerate(cards, start=1):
    await card.screenshot({'path': f'card-{index}.png'})

Layout changes after selection

Keep the selected handle only as long as the page’s DOM remains stable. If a framework replaces that node during a render, the handle can become detached. Wait for the final state, then select the element again immediately before capturing.

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

Screenshot options you can pass

ElementHandle.screenshot() accepts the same screenshot options as Page.screenshot().

Option Use Important detail
path Write an image file. The image type can be inferred from the extension.
type Choose png or jpeg. Use an explicit type when the filename does not make the format clear.
quality Control JPEG compression. Accepts 0–100 and has no effect on PNG.
omitBackground Hide the default white page background. Useful when you need transparency-capable output.
encoding Return image data rather than only writing a file. Use binary for bytes or base64 for a base64 string.
clip Supply a manual rectangle. Usually unnecessary for the direct element method.

Save bytes instead of a file

Omit path and retain the returned value. This is useful when uploading the image to object storage or returning it from an API:

image_bytes = await element.screenshot({'encoding': 'binary'})
with open('element.png', 'wb') as output:
    output.write(image_bytes)

For a base64 payload, request {'encoding': 'base64'} and pass the resulting string to the system that consumes it.

JPEG output

await element.screenshot({
    'path': 'element.jpg',
    'type': 'jpeg',
    'quality': 85,
})

JPEG quality is ignored for PNG. For text-heavy UI, PNG generally preserves sharp edges; JPEG can reduce size for photographic content.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
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.

Manual bounding-box fallback for precise control

Use boundingBox() and a page-level clip when you need to inspect or adjust the rectangle yourself:

box = await element.boundingBox()
if box is None:
    raise RuntimeError('Element is not visible or has no layout box')

await page.screenshot({
    'path': 'manual-clip.png',
    'clip': {
        'x': box['x'],
        'y': box['y'],
        'width': box['width'],
        'height': box['height'],
    },
})

boundingBox() returns None when the element is not visible. The manual approach gives you an explicit rectangle, but it also makes you responsible for checking dimensions and coordinates. The direct element method is less error-prone for ordinary captures because it handles the layout offsets internally before calling the page screenshot implementation.

Why is my element screenshot blank or throwing an error?

“No element matched the selector”

  • Confirm spelling, punctuation, and whether the element is inside an iframe.
  • Wait for the relevant DOM with page.waitForSelector().
  • Check that the page navigation reached the expected URL rather than an error or redirect page.

The element is invisible or boundingBox() is None

  • Capture after the element is displayed and has completed layout.
  • Inspect whether CSS sets display: none, visibility: hidden, zero dimensions, or an off-screen state.
  • For animated interfaces, wait for the animation or disable it with page CSS before measuring.

Detached-element errors

A framework re-render can replace the node after you selected it. Pyppeteer documents an ElementHandleError for a detached element. Wait for the render to settle, call querySelector() again, and screenshot the fresh handle instead of retrying the stale one.

The crop is unexpected

The direct method captures the element’s box, not its parent, shadow, or overflowing siblings. Check padding, borders, CSS transforms, and the element’s scroll position. If you need a deliberately expanded or offset rectangle, use the manual boundingBox() fallback.

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

The image is blank even though the selector matched

  • The node may have dimensions but no painted content yet; wait for data, fonts, and images to finish loading.
  • A white element on a transparent or white background can appear empty; try a contrasting page background while debugging.
  • Verify that the selected node is the visible instance when duplicate responsive layouts exist.

Browser startup or Chromium download failures

Install the package with python3 -m pip install pyppeteer, then run pyppeteer-install to fetch the bundled Chromium revision. Check filesystem permissions, network access during installation, and that your runtime uses the same environment where the package and browser were installed.

Reliability and performance practices

Wait for the state you intend to document

page.goto() returning does not guarantee that a single-page application has finished rendering. Combine an appropriate navigation wait with a specific selector, and add a short deliberate delay only when a known animation or delayed widget requires it. Waiting for a meaningful DOM condition is more reliable than using a large fixed sleep.

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

Reuse the browser process

For multiple captures, launch one browser and create or reuse pages rather than starting Chromium for every element. Close pages and the browser in a finally block in production code so failed jobs do not leave processes running.

Control output size

Capture only the element you need, choose PNG or JPEG deliberately, and request bytes when you are streaming the result instead of writing temporary files. Element screenshots are already smaller than full-page captures because the clip is limited to the node’s box.

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

Account for dynamic content

Ads, rotating banners, timestamps, lazy images, and responsive breakpoints can change the box between runs. Set a consistent viewport and wait for the content that matters. A scrollable component still represents its current scroll position, so scroll it explicitly before calling screenshot() when a particular portion is required.

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

Or skip the browser setup

If you do not want to maintain Chromium downloads and Pyppeteer timing, ScreenshotNeo provides a website screenshot API. Its element option accepts a CSS selector, while the service can also wait for a selector, delay, or network idle and apply custom JavaScript or CSS.

For a normal page shot, call the API as follows (replace the URL with the page you need):

curl -G "https://api.screenshotneo.com/v1/shot" -d access_key=YOUR_API_KEY --data-urlencode url=https://stripe.com -o shot.webp

Python:

import requests
r = requests.get("https://api.screenshotneo.com/v1/shot", params={"access_key": "YOUR_API_KEY", "url": "https://stripe.com"}, timeout=90)
open("shot.webp", "wb").write(r.content)

Node.js:

const q = new URLSearchParams({ access_key: 'YOUR_API_KEY', url: 'https://stripe.com' });
const res = await fetch(`https://api.screenshotneo.com/v1/shot?${q}`);

See the ScreenshotNeo documentation for the selector parameter and the other request options. Before capture, it accepts cookie and consent banners and removes more than 60 known consent platforms, newsletter popups, and chat widgets; each cleanup step can be disabled. Bot checks or CAPTCHAs, blank pages, timeouts, failed loads, and cache hits are not billed, and response headers identify the page verdict and billing result. An MCP server exposes take_screenshot, get_page_info, and capture_pdf for Claude, Cursor, and other MCP clients. The Free plan includes 1,000 screenshots per month with no card; paid plans start at $5 for 3,000 shots. Create a free ScreenshotNeo account.

What’s actually slowing this PC down?

Pick the symptom - the matching free tool is one click away.

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

Pyppeteer versus a manual clip

Approach Simplicity Control Failure checks Best fit
element.screenshot() One call after selecting a handle. Uses the element’s own box. Check for a null handle and detached or invisible nodes. Routine single-element captures.
boundingBox() plus page.screenshot() More code. Explicit x, y, width, and height. You must handle a missing box and validate the clip. Custom crops, offsets, or diagnostic work.

FAQ

Can Pyppeteer screenshot an element by ID?

Yes. Pass an ID selector such as #receipt to page.querySelector(), verify the returned handle, and call its screenshot() method.

Does an element screenshot include the whole scrollable element?

No. It represents the element’s current visible bounding box. Scroll the component yourself or use a different capture strategy when hidden overflow must be included.

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.

Can I return the image directly from a web service?

Yes. Omit path and request binary or base64 encoding, then send the returned data from your application.

Why should I reselect an element before retrying?

Client-side frameworks may replace the DOM node during rendering. The original handle then points to a detached element, so a fresh selector lookup is required.

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

Frequently Asked Questions

Can Pyppeteer screenshot an element by ID?

Yes. Pass an ID selector such as #receipt to page.querySelector(), verify the returned handle, and call its screenshot() method.

Does an element screenshot include the whole scrollable element?

No. It represents the element’s current visible bounding box. Scroll the component yourself or use a different capture strategy when hidden overflow must be included.

Can I return the image directly from a web service?

Yes. Omit path and request binary or base64 encoding, then send the returned data from your application.

Why should I reselect an element before retrying?

Client-side frameworks may replace the DOM node during rendering. The original handle then points to a detached element, so a fresh selector lookup is required.

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

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.