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.

Some links on this page are affiliate links: if you buy through them we may earn a commission, at no extra cost to you.

Use Selenium’s WebElement.screenshot() method when you need an image of one element rather than the whole browser window. Locate the element, put the page in the intended state, then save it to a PNG path or read the PNG bytes in memory. The method returns True or False for a file save, so you can detect a write failure instead of silently continuing. Selenium documents the operation as “Save a PNG screenshot of the current element to a file” in its official Python implementation.

The shortest working example

This script opens a page, finds the main element with a CSS selector, writes element.png, checks the boolean result, and always closes the browser:

from selenium import webdriver
from selenium.webdriver.common.by import By


driver = webdriver.Chrome()
try:
    driver.get("https://example.com")
    element = driver.find_element(By.CSS_SELECTOR, "main")
    saved = element.screenshot("element.png")
    if not saved:
        raise OSError("Could not save element screenshot")
finally:
    driver.quit()

Use a full destination such as /tmp/example-main.png when a predictable location matters. The Selenium API recommends a full path and a .png extension. A successful call returns True; a local file-writing failure is reported as False by the documented implementation.

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

What an element screenshot captures

element.screenshot(filename) targets the selected WebElement. It is different from a driver screenshot, which represents the current browser window. Selenium’s WebDriver API exposes window-level PNG and base64 screenshot methods.

Need Use Result
One card, form, article, chart, or other selected node element.screenshot("element.png") PNG file containing the current element
One selected element, but no file yet element.screenshot_as_png PNG bytes in memory
One selected element as text for transport element.screenshot_as_base64 Base64-encoded PNG text
The visible browser window driver.save_screenshot("window.png") or the driver PNG/base64 methods Window-level screenshot

The element methods are useful for attaching a focused image to a test report, comparing a component, or sending just one region to another service. They do not change the page; they capture its current rendered state.

Install and prepare Selenium

Install Selenium in the Python environment that will run the script:

python -m pip install selenium

Your execution environment also needs a browser that Selenium can launch and the corresponding WebDriver setup. Keep the browser, driver, and Selenium versions compatible according to the setup documentation for your environment. In CI, run the same setup in the job image rather than assuming a developer’s local browser exists.

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

Before taking the image, decide what “ready” means for the page: a visible component, a particular route, loaded data, or a dismissed dialog. A screenshot is only as accurate as the state you create before the call.

Locate the exact element

Use a locator that identifies the component you actually want. IDs are usually less fragile than styling classes; a stable data attribute can be preferable when the application provides one.

from selenium.webdriver.common.by import By

hero = driver.find_element(By.ID, "hero")
card = driver.find_element(By.CSS_SELECTOR, "article[data-testid='pricing-card']")

If a selector matches several nodes, use find_elements and select deliberately, or narrow the selector. Taking a screenshot of the first accidental match is a targeting bug, not a rendering bug.

Wait for the page state, not an arbitrary delay

Dynamic pages can create the element after navigation or fill it with data later. Prefer an explicit condition that describes the state you need. For example, wait until the target is visible:

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC

wait = WebDriverWait(driver, 20)
element = wait.until(
    EC.visibility_of_element_located((By.CSS_SELECTOR, "main"))
)
element.screenshot("main.png")

A fixed sleep can be too short on a busy run and unnecessarily slow on a fast one. If the element appears before its text, images, or chart data, wait for the application-specific condition instead, such as a status element disappearing or a result count becoming non-empty.

Save to a file, bytes, or base64

Save directly to PNG

The file form is the simplest for reports and artifacts:

path = "/absolute/path/to/component.png"
if not element.screenshot(path):
    raise OSError(f"Screenshot was not saved: {path}")

Check that the parent directory exists and that the test process can write there. A False return is actionable evidence that the file was not written.

Keep PNG bytes in memory

png_bytes = element.screenshot_as_png
if not png_bytes:
    raise ValueError("Element screenshot returned no PNG data")
with open("component.png", "wb") as output:
    output.write(png_bytes)

This avoids an intermediate file when you need to upload the image, attach it to a report, or process it with an image library.

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.

Use base64 when an API requires text

png_base64 = element.screenshot_as_base64
payload = {"name": "component", "image": png_base64}

Base64 is convenient for JSON or data-URI workflows, but it is larger than the underlying bytes. Decode it at the receiving boundary when binary PNG data is preferable.

A robust capture function

Wrapping navigation, location, waiting, and cleanup in one function makes failures easier to diagnose and prevents browsers from being left open:

from pathlib import Path
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


def capture_element(url: str, selector: str, output: str) -> Path:
    destination = Path(output).expanduser().resolve()
    destination.parent.mkdir(parents=True, exist_ok=True)

    driver = webdriver.Chrome()
    try:
        driver.get(url)
        wait = WebDriverWait(driver, 20)
        element = wait.until(
            EC.visibility_of_element_located((By.CSS_SELECTOR, selector))
        )
        if not element.screenshot(str(destination)):
            raise OSError(f"Selenium could not save {destination}")
        return destination
    finally:
        driver.quit()


saved_path = capture_element(
    "https://example.com", "main", "artifacts/example-main.png"
)
print(saved_path)

For a reproducible capture, also control the window size before navigation and perform any clicks or state changes before locating the final element. Keep those actions close to the screenshot call so later page changes cannot invalidate the intended state.

Diagnose wrong, missing, or incomplete captures

NoSuchElementException

The locator did not match at the time it ran. Confirm the URL, inspect the selector in the browser, and wait for the element if it is created asynchronously. If the content is inside an iframe, switch into that frame before locating the element; switch back afterward when the rest of the test needs the top-level document.

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

StaleElementReferenceException

The page replaced the node after you found it. Wait for the update to finish, locate the element again, and capture the new reference. Do not keep retrying the same stale object.

The screenshot is of the wrong component

Log or inspect the selector and compare the element’s size and location with what you expect. Selenium exposes element size and location helpers for this diagnosis. The location_once_scrolled_into_view property can help inspect where Selenium places an element, but its documentation cautions that its behavior may change without warning; treat it as a diagnostic helper, not as a stable screenshot contract. See the WebElement source and API implementation.

The file is missing even though the script continued

Check the boolean return, use an absolute path, verify the parent directory and permissions, and confirm that another process is not removing the artifact. Raising on False turns a silent artifact loss into a test failure.

The element is blank or visually unfinished

The node may exist before its data, fonts, images, or canvas drawing is ready. Wait for the application’s ready signal, not merely DOM presence. If a cookie dialog, newsletter overlay, or chat widget covers the component, close it before locating or capturing the target. If the target is intentionally hidden, make it visible through the same user action your test is meant to document.

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

The image does not include content below the viewport

An element screenshot is tied to the element Selenium renders; it is not a general-purpose full-page capture. For an entire long document, use a window or full-page capture strategy appropriate to your browser and test goal. If you need only a specific component, first verify that the element’s rendered dimensions include the content you expect.

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

Performance and reliability practices

  • Capture only the required element instead of repeatedly saving full windows; smaller artifacts are easier to store and review.
  • Reuse a driver for a sequence of related captures when isolation is not required, but reset application state between cases.
  • Use deterministic selectors and explicit waits so retries do not depend on timing luck.
  • Write artifacts to unique paths in parallel runs to prevent one worker from overwriting another.
  • Record the URL, selector, viewport configuration, and failure exception with the image. That context is often more valuable than the image alone.
  • Always call driver.quit() in a finally block, including when locating or saving fails.

Or skip the browser setup

If you only need a URL turned into a clean element or page image, ScreenshotNeo provides a website screenshot API and MCP server. Its capture options include selecting one element by CSS selector, full-page capture with lazy images loaded, custom CSS and JavaScript, clicks before capture, waits for a selector, delay or network idle, dark mode, device presets, arbitrary viewports, retina scale, image resizing, transparent backgrounds, request blocking, custom headers/cookies/user agents, timezone and geolocation, caching with a chosen TTL, signed links, asynchronous jobs with signed webhooks, bulk capture of up to 100 URLs per call, and PDF output.

Here is the one-call cURL form (set the element option in your request when you want a CSS-selected element). The complete parameter reference is in the ScreenshotNeo documentation:

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,
)
r.raise_for_status()
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}`);
if (!res.ok) throw new Error(`Screenshot failed: ${res.status}`);
const fs = await import('node:fs/promises');
await fs.writeFile('shot.webp', Buffer.from(await res.arrayBuffer()));

ScreenshotNeo accepts and reports page verdict and billing status through X-Page-Verdict and X-Billed headers. Cookie and consent banners, newsletter popups, and chat widgets can be removed before capture. Bot checks or CAPTCHAs, blank pages, timeouts, failed loads, and cache hits are not billed. Its MCP server exposes take_screenshot, get_page_info, and capture_pdf for Claude, Cursor, and other MCP clients.

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

The Free plan includes 1,000 screenshots per month with no card. Paid plans start at $5 for 3,000 shots; Growth is $15 for 15,000, Pro $39 for 60,000, Scale $99 for 250,000, and Business $249 for 1,000,000. Yearly billing gives two months free, and every feature is available on every plan. Create a free ScreenshotNeo account to get the 1,000 monthly screenshots without a card.

Choosing the right approach

Situation Best fit Why
You are already testing a page in Selenium and need one component WebElement.screenshot() No second service or upload step; the image comes from the test’s current browser state.
You need bytes or base64 for an existing Python pipeline screenshot_as_png or screenshot_as_base64 Avoids temporary files.
You need clean captures across many URLs or from AI tools ScreenshotNeo Element selection, cleanup controls, API/MCP access, and billing that excludes failed or blocked captures.

For Selenium-based assertions, keep the capture inside the test so it reflects the exact state under test. For scheduled previews, bulk URL work, or agent-driven capture where maintaining browsers is unnecessary, the API route removes that setup.

Frequently Asked Questions

Can Selenium return an element screenshot without writing a file?

Yes. Read element.screenshot_as_png for PNG bytes or element.screenshot_as_base64 for base64 text, then pass that value to your report or upload code.

Which Selenium method should I use for a whole browser window?

Use the WebDriver screenshot methods, such as driver.save_screenshot(). WebElement.screenshot() is specifically for the selected element.

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

Why does Selenium report success but my image is visually wrong?

A successful save only confirms that an image was written. Recheck the locator and page state, wait for dynamic content, and inspect the element’s size and location before capturing.

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.