Do these 3 things before closing this tab:
1Scan for outdated or missing drivers - takes under a minute2Clear out junk files and repair common Windows errors3Fix the driver behind crashes, sound loss and screen glitchesTo capture one element rather than the browser window, locate it as a WebElement and call its screenshot method. In Python, use element.screenshot("element.png"); in Java, call getScreenshotAs on the element. Calling the screenshot method on the driver instead captures the current browser window, not just that element.
Capture one element in Python
Find the element after the page has loaded, then call its screenshot() method. This example opens a page, locates an element by CSS selector, and writes its screenshot as a PNG:
from pathlib import Path
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.support.ui import WebDriverWait
output = Path("screenshots/element.png")
output.parent.mkdir(parents=True, exist_ok=True)
driver = webdriver.Chrome()
try:
driver.get("https://example.com")
element = WebDriverWait(driver, 10).until(
EC.visibility_of_element_located((By.CSS_SELECTOR, "#target"))
)
saved = element.screenshot(str(output))
if not saved:
raise OSError(f"Could not write screenshot to {output}")
finally:
driver.quit()
Replace https://example.com with the page you control or are authorized to automate, and replace #target with a selector that matches the desired element. The wait prevents an immediate lookup from racing the page load; visibility_of_element_located also checks that the element is visible before capture. The output directory is created explicitly because Selenium does not create missing parent directories for you.
Save as a file, bytes, or Base64
Python’s WebElement.screenshot(filename) writes a PNG file and returns a Boolean: True when the write succeeds and False when an I/O error occurs. The Selenium Python API describes it as saving a screenshot of the current element to a PNG image file. Use a filename ending in .png; the element screenshot API is not a general JPEG or WebP encoder.
Outdated 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 matchWindows Errors? Fix Them Before They Spread
Repair common Windows errors and clear accumulated junk for a smoother, more stable PC - no reinstall needed.Free scan · no reinstall#1 Best Overall
If the next step in your program needs image data rather than a file, get the PNG bytes from screenshot_as_png, or the encoded text from screenshot_as_base64:
png_bytes = element.screenshot_as_png
base64_text = element.screenshot_as_base64
with open("screenshots/element.png", "wb") as image_file:
image_file.write(png_bytes)
Binary mode ("wb") matters: it writes the PNG bytes unchanged. Base64 is useful when a receiving interface expects text, but it is not itself a PNG file; decode it before saving it as an image.
Capture an element in Java
In Java, WebElement implements Selenium’s TakesScreenshot interface. Cast the located element to that interface, then select the output type. This example saves the returned temporary file to a known path and also shows how to obtain Base64:
Rank #2
import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.StandardCopyOption;
import org.openqa.selenium.By;
import org.openqa.selenium.OutputType;
import org.openqa.selenium.TakesScreenshot;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.WebDriverWait;
import java.time.Duration;
public class ElementScreenshot {
public static void main(String[] args) throws IOException {
WebDriver driver = new ChromeDriver();
try {
driver.get("https://example.com");
WebElement element = new WebDriverWait(driver, Duration.ofSeconds(10))
.until(ExpectedConditions.visibilityOfElementLocated(
By.cssSelector("#target")));
File temporaryFile = ((TakesScreenshot) element)
.getScreenshotAs(OutputType.FILE);
Path destination = Path.of("screenshots", "element.png");
Files.createDirectories(destination.getParent());
Files.copy(temporaryFile.toPath(), destination,
StandardCopyOption.REPLACE_EXISTING);
String base64 = ((TakesScreenshot) element)
.getScreenshotAs(OutputType.BASE64);
} finally {
driver.quit();
}
}
}
Change the page URL and selector for your case. OutputType.FILE provides a file you can copy to a durable location; OutputType.BASE64 returns encoded text. Selenium’s Java API also supports other output targets accepted by OutputType. The temporary file may not live at your intended destination, so copy it if the image must remain at a predictable path.
What’s actually slowing this PC down?
Pick the symptom - the matching free tool is one click away.
Why the result may show the whole browser window
Screenshot scope depends on the object receiving the call. An element-level method requests an image of one DOM element. A driver-level method requests the current browser window. In Python, use element.screenshot(...) for the former; driver.save_screenshot(...) or driver.get_screenshot_as_file(...) for the latter. If your output includes the page around the target, check that you did not call the driver method by mistake.
The Java TakesScreenshot API can be used with a driver or an HTML element. Its description says it indicates a driver or element that can capture a screenshot and store it in different ways. Make sure the object you cast and call is the WebElement you located, rather than the WebDriver.
Rank #3
Make the capture reliable
Wait for the right state
A successful locator lookup does not guarantee that a dynamic element has finished rendering or stopped moving. For asynchronously loaded content, wait for the specific condition your page needs: presence, visibility, or a relevant state change. If the element changes during capture, wait for the update to finish or for the page to become stable. A fixed sleep can work in a controlled test, but an explicit wait tied to the page condition is generally more robust.
Choose and verify the locator
Prefer a stable ID or a CSS selector that clearly identifies one element. If the selector matches the wrong element, Selenium can produce a valid screenshot of the wrong target. When investigating, check the selected element’s text, attributes, or count before capture. If the element is inside an iframe, switch into that frame before finding it; Selenium searches the current browsing context, not every frame at once.
Handle off-screen or changing elements
Element screenshot behavior can depend on the WebDriver implementation. The Selenium Java API describes W3C-conformant implementations as following the W3C WebDriver specification; for non-conformant implementations, Selenium documents best-effort behavior that prefers the entire element content and then the visible portion. Do not assume every browser captures an off-screen or unusually large element identically. If capture fails or is incomplete, scroll the element into view, wait for it to settle, and try again. For a specific browser and driver, check the documentation for the Selenium binding and implementation you are using.
Common errors and fixes
- No such element: The selector may be wrong, the page may not have loaded the target yet, or the element may be in an iframe. Verify the selector, wait for the page condition, and switch to the correct frame before locating it.
- Stale element reference: The page replaced or re-rendered the element after it was located. Wait for the updated page state, locate the element again, and take the screenshot from the fresh reference.
- Python returns
Falseor the file is missing: The image write encountered an I/O problem. Use a writable full path, create its parent directory, and check permissions and available disk space. The Python implementation obtains the PNG bytes, writes them in binary mode, and returnsFalseon anOSError. - Java throws
WebDriverException: Screenshot capture failed in the driver or browser. Confirm that the browser session is still active, the element is valid, and the implementation supports element screenshots; then retry after the page reaches a stable state. UnsupportedOperationException: The implementation does not support the requested operation. The Selenium Java API documents this possibility for unsupported implementations. Use a W3C-conformant WebDriver/WebElement implementation or a supported alternative capture method for your use case.- The image is clipped or differs across browsers: Behavior may vary, especially for non-conformant implementations or elements outside the viewport. Scroll into view, wait for layout changes to finish, and compare using the same browser and driver configuration.
- Only part of a lazy-loaded component appears: Content may load only after scrolling or interaction. Trigger the page behavior that loads the content, wait until it appears, and then capture the element.
Or skip the browser setup
If you need a screenshot of a website by URL rather than a specific DOM element, ScreenshotNeo provides a screenshot API and MCP server. It is not a Selenium WebElement capture replacement: use the Selenium methods above when you need one element from an existing browser session. For URL-based captures, one GET request can return PNG, JPEG, WebP, or PDF. See the ScreenshotNeo documentation for request options.
curl -G "https://api.screenshotneo.com/v1/shot" -d access_key=YOUR_API_KEY --data-urlencode url=https://stripe.com -o shot.webp
Python version:
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 version:
const q = new URLSearchParams({ access_key: 'YOUR_API_KEY', url: 'https://stripe.com' });
const res = await fetch(`https://api.screenshotneo.com/v1/shot?${q}`);
ScreenshotNeo accepts cookie or consent banners like a visitor and removes more than 60 known consent platforms, newsletter popups, and chat widgets before capture; each of those steps can be turned off. Bot checks, blank pages, timeouts, failed loads, and cache hits are not billed, and response headers identify the page verdict and billing status. An MCP server exposes screenshot tools for Claude, Cursor, and other MCP clients. The Free plan includes 1,000 shots per month without a card; paid plans start at $5 for 3,000 shots. Sign up for free and get 1,000 screenshots a month with no card.
Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.Cost, output, and operational notes
Selenium is the direct choice when the screenshot must come from an automated browser session you already control—for example, a test verifying a component after interaction. Your code owns browser startup, waits, file handling, and any test infrastructure. Element screenshot methods return PNG data; choose bytes or Base64 if you need to pass the result onward rather than save a file.
Quick wins for a faster PC:
Clear out junk files and repair common Windows errorsFree Scan →Scan for outdated or missing drivers - takes under a minuteDriver Scan →Repair Windows errors before they cause bigger problemsFix Now →A URL screenshot service solves a different operational problem: capturing a rendered page without managing the browser setup in the calling application. ScreenshotNeo offers URL-level captures and options including selecting an element by CSS selector, waiting for a selector or network idle, custom JavaScript and CSS, and caching with a chosen TTL. Those options can be useful for repeatable page captures, but they do not give you access to the live Selenium session or its current interactive state. Check the returned verdict and billing headers when handling non-successful or cached requests, and set a request timeout appropriate to your own application.
Best Value
FAQ
Can I get screenshot bytes without writing an image file?
Yes. In Python, read element.screenshot_as_png; in Java, request an output type such as OutputType.BASE64 when encoded text is useful.
Can Selenium save an element screenshot directly as JPEG?
The element screenshot methods described here produce PNG output. If your workflow requires JPEG, convert the PNG afterward with an image-processing library.
Does an element screenshot always include the entire element?
No universal guarantee applies across all implementations. W3C-conformant support follows the WebDriver specification; Selenium documents best-effort fallback behavior for non-conformant elements, preferring full content and then the visible portion.
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.

