Use Selenium’s WebElement.screenshot() method when you need an image of one DOM element rather than the entire browser window. Locate the element, wait until the page is in the required state, then save a PNG and check the returned Boolean:
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()
When copying the example, remove the extra leading space before driver. The method is documented by Selenium as: “Save a PNG screenshot of the current element to a file.”
What an element screenshot captures
element.screenshot(filename) captures the selected WebElement’s rendered bounds. It is different from driver.save_screenshot(filename), which captures the current browser window. Use the element method for a card, chart, article, form, navigation region or other specific component; use the driver method when the whole viewport is the subject.
The Python implementation writes a PNG file and returns True when the save succeeds or False when the local file write fails. Selenium’s official WebElement implementation is available at github.com/SeleniumHQ/selenium/blob/trunk/py/selenium/webdriver/remote/webelement.py.
#1 Best Overall
Prerequisites and setup
- Python 3 and a virtual environment (recommended).
- Selenium installed with
python -m pip install selenium. - A browser supported by Selenium, such as Chrome, and its driver management configured for your environment.
- A writable destination ending in
.png. Selenium recommends providing a full path when a predictable location matters.
Create a project, install Selenium, and verify that your browser starts before adding application-specific locators. In CI, run the browser in the mode required by your environment (for example, a configured headless session) and ensure the process can write to the target directory.
Basic, copy-ready example
from pathlib import Path
from selenium import webdriver
from selenium.webdriver.common.by import By
output = Path("element.png").resolve()
driver = webdriver.Chrome()
try:
driver.get("https://example.com")
element = driver.find_element(By.CSS_SELECTOR, "main")
saved = element.screenshot(str(output))
if not saved:
raise OSError(f"Selenium could not save {output}")
print(f"Saved {output}")
finally:
driver.quit()
find_element returns the first matching element. Replace main with a locator that uniquely identifies the component you intend to document. The full-path conversion avoids confusion about the process’s current working directory.
Reliable capture workflow
-
Navigate
Call
driver.get(url)and wait for the page condition that defines “ready” for your capture. A fixed sleep is not universally required and can be either too short or unnecessarily slow. -
Locate the element
Prefer stable IDs or deliberate CSS selectors over brittle positional selectors. For example,
By.ID, "invoice-summary"is usually clearer than a chain of generated classes.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. -
Put the page in its final state
Dismiss overlays when your test requires it, select tabs, expand accordions, or trigger rendering before taking the image. The screenshot reflects the state that exists at the instant Selenium captures it.
-
Save and validate
Pass a full path with a
.pngextension, inspect the Boolean return value, and raise or log a useful error when it isFalse. -
Close the session
Use
finallyso the browser is quit even if navigation, locating, or writing fails.
Locating the correct element
ID and CSS selectors
summary = driver.find_element(By.ID, "summary")
summary.screenshot("summary.png")
hero = driver.find_element(By.CSS_SELECTOR, "section.hero[data-state='ready']")
hero.screenshot("hero.png")
Keep selectors tied to attributes your application treats as stable. If several elements match, use find_elements to inspect the count or refine the selector rather than silently capturing the first match.
Quick wins for a faster PC:
Fix the driver behind crashes, sound loss and screen glitchesFind Drivers →Clear out junk files and repair common Windows errorsFree Scan →Diagnosing size and position
Selenium exposes an element’s size and location, which help explain an unexpectedly small or empty image:
print(element.size)
print(element.location)
The location_once_scrolled_into_view helper can scroll and report coordinates, but Selenium documents a caution that its behavior may change without warning. Treat it as a diagnostic aid, not as a stable screenshot contract.
Waiting for dynamic content
Modern pages often render an element before its contents are complete. Use an explicit wait for a meaningful condition, such as presence or visibility, and add an application-specific condition for charts, images, or loading indicators when needed:
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")
Visibility only proves that Selenium can see the element; it does not prove that every asynchronous child has finished. If your page exposes a “loaded” class, a completed request marker, or a non-loading state, wait for that signal instead of guessing with a long delay.
Do these 3 things before closing this tab:
1Repair Windows errors before they cause bigger problems2Scan for outdated or missing drivers - takes under a minute3Clear out junk files and repair common Windows errorsSaving to a file, bytes, or Base64
PNG file
The normal API is element.screenshot("/full/path/element.png"). It returns a Boolean, so check it when a missing artifact would invalidate a test or build.
PNG bytes in memory
png_bytes = element.screenshot_as_png
with open("element.png", "wb") as image_file:
image_file.write(png_bytes)
screenshot_as_png is useful when uploading directly to an object store, attaching an image to a test report, or processing it without an intermediate file.
Base64 text
encoded = element.screenshot_as_base64
html_img = f"<img alt="Element" src="data:image/png;base64,{encoded}">"
screenshot_as_base64 returns the encoded representation as text. Do not confuse this with a file path; decode it or embed it according to the API that consumes it.
Element versus window screenshots
| Need | Use | Result |
|---|---|---|
| One selected DOM element | element.screenshot(filename) |
PNG of that element |
| Element image in memory | element.screenshot_as_png |
PNG bytes |
| Element as encoded text | element.screenshot_as_base64 |
Base64 string |
| Current browser window | driver.save_screenshot(filename) or driver PNG methods |
Window-level screenshot |
The WebDriver API reference for window screenshots is at selenium.dev/selenium/docs/api/py/selenium_webdriver_remote/selenium.webdriver.remote.webdriver.html.
Common failures and fixes
NoSuchElementException
Cause: the selector does not match yet, is incorrect, or the element is inside a frame. Fix: verify the selector in browser developer tools, wait for the element, and switch to the correct iframe before locating it.
StaleElementReferenceException
Cause: the page replaced the node after you located it. Fix: wait for the update to finish, then locate the element again immediately before the screenshot.
Screenshot is blank or incomplete
Cause: capture occurred before asynchronous content, fonts, or images finished. Fix: wait on a real application readiness condition and confirm the element’s size. A zero width or height usually indicates that it is hidden, collapsed, or not yet laid out.
Wrong component is captured
Cause: a broad selector matched an unintended element. Fix: narrow the CSS or ID selector, inspect element.location and element.size, and verify the page state before capture.
PC Slower Than It Used to Be?
A free scan shows the junk files, broken settings and background clutter dragging Windows down - then fixes them in one click.Free scan · Windows 10 & 11Outdated Drivers Are Slowing You Down
One free scan finds every outdated or missing driver and matches the right update for your exact hardware.Free scan · exact hardware matchBest Value
Return value is False or the file is missing
Cause: the destination is unwritable, its parent directory does not exist, or a local OSError occurred during writing. Fix: create the directory, use an absolute path, check permissions, and retain the Boolean check.
Overlay obscures the target
Cause: a cookie dialog, modal, newsletter prompt, or chat widget is covering the page. Fix: handle the overlay in your test flow before locating or capturing the target. Do not hide it if the overlay itself is what you are testing.
Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.Performance and reliability considerations
- Reuse one driver session for related captures, but isolate tests when page state can leak between cases.
- Use explicit waits tied to application signals; arbitrary sleeps increase runtime and still race under slow conditions.
- Write to local storage first when a test runner needs an artifact, then upload or archive it after the browser closes.
- Use deterministic viewport and browser settings when comparing images across runs. The element method limits the output to the element, but fonts, responsive breakpoints, animations, and device pixel behavior can still change pixels.
- Disable or wait for animations when visual comparison requires stable frames.
- Keep filenames unique in parallel jobs to prevent workers from overwriting one another.
Or skip the browser setup
ScreenshotNeo provides a website screenshot API and MCP server. Its element capture option can target a CSS selector, while other options cover full-page shots, device viewports, retina scale, waiting conditions, custom JavaScript and CSS, headers, cookies, blocking requests, PDFs, signed links, asynchronous jobs and bulk capture.
A single GET request returns an image or PDF:
curl -G "https://api.screenshotneo.com/v1/shot" -d access_key=YOUR_API_KEY --data-urlencode url=https://stripe.com -o shot.webp
For 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)
For 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 complete parameter reference at ScreenshotNeo’s documentation. Before capture it accepts cookie and consent banners and removes more than 60 known consent platforms, newsletter popups and chat widgets; each step can be turned off. Bot checks and CAPTCHAs, blank pages, timeouts, failed loads and cache hits are not billed as clean shots, and response headers identify the page verdict and billing result. Its MCP server lets Claude, Cursor and other MCP clients call take_screenshot, get_page_info and capture_pdf. The Free plan includes 1,000 shots each month without a card; paid plans start at $5 for 3,000 shots. Sign up for the free plan.
FAQ
Does Selenium save element screenshots as JPEG?
The documented WebElement method saves a PNG. Convert the resulting bytes with an image-processing library if another format is required.
Can I capture an element that is outside the viewport?
The WebElement screenshot targets the element, but page layout and browser behavior still matter. Confirm the element is rendered and use Selenium’s location and size properties when diagnosing unusual results.
Should I use a fixed sleep before every screenshot?
No. Wait for the condition that represents readiness on your page; a fixed delay is only appropriate when a known, unavoidable timing requirement cannot be expressed more precisely.
Quick Recap
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.
Recommended Free Tools

