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 WebDriver’s screenshot command after navigating to the page and waiting for the state you want to record. In Python, driver.save_screenshot("artifacts/home.png") writes a PNG; use get_screenshot_as_png() for bytes or get_screenshot_as_base64() when the image must be embedded or sent to another service. The same workflow applies to Java, JavaScript, C#, Ruby and remote drivers: create a driver, navigate, wait, capture the current browsing context or an element, handle the result, and always quit the driver.
What Selenium captures
A screenshot records the current browsing context at the instant the command runs. It is normally the visible browser viewport, not automatically an entire document. The result can be saved as a PNG file, kept as binary data, or returned as a Base64 string. A page screenshot and an element screenshot are separate operations.
- Browsing-context screenshot: captures the current page view.
- Element screenshot: captures one located WebElement, such as a heading, chart or error panel.
- File output: creates a PNG artifact for test reports or debugging.
- Bytes or Base64: avoids a temporary file when uploading, embedding or processing the image.
Image dimensions and full-page behavior can differ between browser and driver implementations. For repeatable results, record the browser, driver, viewport, operating system, Selenium binding version and whether the run used a local or remote driver.
Free tools Windows power users keep installed
One-click scans. No signup required.
Python: save a page screenshot
Install Selenium, ensure Chrome and a compatible driver are available, create the output directory, then run this complete example:
#1 Best Overall
from pathlib import Path
from selenium import webdriver
output = Path("artifacts")
output.mkdir(parents=True, exist_ok=True)
driver = webdriver.Chrome()
try:
driver.get("https://example.com")
ok = driver.save_screenshot(str(output / "home.png"))
if not ok:
raise IOError("Selenium could not write the screenshot")
finally:
driver.quit()
save_screenshot(filename) and get_screenshot_as_file(filename) are PNG file helpers. Use a full, writable path ending in .png. Python returns False when it cannot write the file, so check the return value instead of assuming the artifact exists.
Capture bytes or Base64 in Python
png_bytes = driver.get_screenshot_as_png()
base64_text = driver.get_screenshot_as_base64()
Bytes are convenient for an HTTP upload or an image library. Base64 can be placed directly in an HTML data URL, for example data:image/png;base64,.... These calls capture the same current context as the file helper.
Capture one WebElement
Wait until the target is present and then call the element’s screenshot method:
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 glitchesfrom selenium.webdriver.common.by import By
header = driver.find_element(By.CSS_SELECTOR, "h1")
if not header.screenshot("artifacts/header.png"):
raise IOError("Could not save element screenshot")
Use a stable selector rather than a generated class name. The element must be available in the current browsing context; if it is inside an iframe, switch into that frame before locating it. An element screenshot is useful for a component-level visual test and avoids capturing unrelated page content.
Java
Java exposes screenshots through the TakesScreenshot interface. The documented file pattern uses OutputType.FILE and copies the temporary file to your chosen path:
Rank #2
import java.io.File;
import java.io.IOException;
import org.apache.commons.io.FileUtils;
import org.openqa.selenium.OutputType;
import org.openqa.selenium.TakesScreenshot;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
WebDriver driver = new ChromeDriver();
try {
driver.get("https://example.com");
File file = ((TakesScreenshot) driver).getScreenshotAs(OutputType.FILE);
FileUtils.copyFile(file, new File("artifacts/home.png"));
} finally {
driver.quit();
}
OutputType.BASE64 returns a string when a file is not wanted. A driver or element can implement TakesScreenshot. Handle WebDriverException for capture failures and UnsupportedOperationException when a particular implementation does not support screenshots.
Java element capture
WebElement card = driver.findElement(By.cssSelector(".pricing-card"));
File file = card.getScreenshotAs(OutputType.FILE);
FileUtils.copyFile(file, new File("artifacts/pricing-card.png"));
JavaScript with Selenium WebDriver for Node.js
The Node.js binding returns a Base64 string from takeScreenshot(). Write it with the Base64 encoding:
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 & 11Crashes, No Sound, or Screen Glitches?
Random freezes, missing sound and display glitches usually trace back to one bad driver. Find and replace yours safely.Free scan · under a minuteconst { Builder } = require('selenium-webdriver');
const fs = require('node:fs');
(async function () {
const driver = await new Builder().forBrowser('chrome').build();
try {
await driver.get('https://example.com');
const encoded = await driver.takeScreenshot();
fs.mkdirSync('artifacts', { recursive: true });
fs.writeFileSync('artifacts/home.png', encoded, 'base64');
} finally {
await driver.quit();
}
}());
For a single element, locate it and call await element.takeScreenshot(true). The Boolean argument requests scrolling the element into view before capture where supported.
C# and Ruby
C#
C# uses the ITakesScreenshot interface:
var driver = new ChromeDriver();
try
{
driver.Navigate().GoToUrl("https://example.com");
var screenshot = ((ITakesScreenshot)driver).GetScreenshot();
screenshot.SaveAsFile("artifacts/home.png");
}
finally
{
driver.Quit();
}
Element screenshot support is available through the element screenshot API in the C# binding. Check the returned screenshot and save it only after creating a writable artifacts directory.
Ruby
driver = Selenium::WebDriver.for :chrome
begin
driver.navigate.to "https://example.com"
driver.save_screenshot("./artifacts/home.png")
ensure
driver.quit
end
Ruby follows the same navigate, capture and cleanup sequence. Element capture is available from the located element.
Make captures reliable in tests and CI
- Create the driver. Select the browser and configure its viewport or device emulation before navigation.
- Navigate. Call
get,Navigate().GoToUrlor the equivalent binding method. - Wait for the required state. A screenshot taken before an AJAX-rendered chart, font, cookie decision or image is ready will faithfully capture the incomplete state. Prefer an explicit wait for a selector or condition over an arbitrary sleep.
- Prepare a deterministic path. Create the directory first and include a test name, browser and timestamp when parallel jobs could overwrite one another.
- Capture and validate. Check Python’s Boolean result, catch Java exceptions and verify that the returned bytes or Base64 string is non-empty.
- Clean up. Put
quit(),quit()in JavaScript, or the binding’s equivalent in afinally/ensureblock.
Waiting for a target
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, 15)
hero = wait.until(EC.visibility_of_element_located((By.CSS_SELECTOR, "[data-testid='hero']")))
hero.screenshot("artifacts/hero.png")
Waiting for visibility confirms that the element can be seen; it does not guarantee that every image, animation or web font has finished. If visual stability matters, wait for the application’s own “ready” signal, disable animations in test CSS, or wait for a specific network-driven result.
Viewport, full-page and remote-driver considerations
Viewport versus full page
Standard WebDriver screenshot behavior is implementation-dependent for dimensions and full-page output. A tall page may produce only the visible viewport, and browser-specific options may change that behavior. If you need a reproducible full-page image, set a known window size and use a browser-specific full-page facility only after confirming its behavior in your target browser. Do not assume that a screenshot from Chrome, Firefox and a remote grid will have identical dimensions.
RemoteWebDriver
Remote execution still follows the same API: navigate on the remote session, wait, call the screenshot command, then save the returned file or data on the machine running the test client. The remote node’s display, browser version, device scale factor and viewport can affect the pixels. Record those values with the artifact.
Frames and windows
Selenium captures the current window and frame context. Switch to the correct window with the window handle API, and call switch_to.frame (or the binding equivalent) before locating an element inside an iframe. Switch back to the default content when the next capture belongs to the outer page.
Output choices and trade-offs
| Need | Use | Reason |
|---|---|---|
| Test artifact | PNG file helper | Easy to attach to CI reports and inspect locally. |
| Upload to an API | PNG bytes | Avoids temporary-file cleanup and preserves binary data. |
| Inline HTML report | Base64 | Can be embedded in a data URL or JSON payload. |
| Component visual test | Element screenshot | Limits the image to one located WebElement. |
PNG is the format documented by the file helpers and is lossless. If a downstream system requires JPEG or WebP, convert the bytes after capture rather than expecting every WebDriver binding to provide those formats.
Quick wins for a faster PC:
Scan for outdated or missing drivers - takes under a minuteDriver Scan →Clear out junk files and repair common Windows errorsFree Scan →Fix the driver behind crashes, sound loss and screen glitchesFind Drivers →Troubleshooting
No file appears
Check that the directory exists, the process has write permission, the path is not a directory, and the filename ends in .png. In Python, a False return indicates an I/O failure. In Java, inspect the caught WebDriverException and the destination path.
The screenshot is blank or incomplete
The command may have run before navigation, rendering or an asynchronous component completed. Wait for a meaningful application condition, confirm that the expected URL loaded, and check that the selected window and frame are correct.
Element not found or element capture fails
Use an explicit wait, verify the selector in the current DOM, scroll the element into view if necessary, and account for iframes or shadow DOM. A detached element must be located again after the page re-renders.
Unsupported screenshot operation
Some driver implementations do not support screenshots or expose only partial behavior. Verify browser-driver compatibility and use a W3C-conformant implementation. Java may report UnsupportedOperationException; other bindings can raise a WebDriver-specific exception.
Different pixels in CI
Fix the viewport, browser version, device scale factor, fonts, timezone and locale. Disable animations where appropriate, wait for stable content, and keep screenshots from the same driver/browser combination when comparing images.
Best Value
Base64 file cannot be opened
Write the returned value as Base64, not as ordinary text bytes. In Node.js use fs.writeFileSync(path, encoded, 'base64'). In other languages, decode the Base64 string before writing binary output.
Or skip the browser setup
For a server-side screenshot without maintaining Selenium, ScreenshotNeo accepts one GET request and returns PNG, JPEG, WebP or PDF. Its cleanup steps accept cookie/consent banners and remove more than 60 known consent platforms, newsletter popups and chat widgets before capture; each step can be disabled. Bot checks, CAPTCHAs, blank pages, timeouts, failed loads and cache hits are not billed, and response headers report the page verdict and billing status.
Using the API is a separate approach from WebDriver: you provide the URL and options, rather than driving a local browser session.
Recommended Free Tools
curl -G "https://api.screenshotneo.com/v1/shot" -d access_key=YOUR_API_KEY --data-urlencode url=https://stripe.com -o shot.webp
See the ScreenshotNeo documentation for all 63 options, including full-page lazy-image loading, CSS-selector element capture, dark mode, device presets and custom viewports, retina scale, PDF paper settings and page ranges, custom CSS and JavaScript, click-before-capture, waits, request blocking, headers, cookies, user agent, Authorization, timezone, geolocation, transparent backgrounds, resizing, chosen cache TTLs, signed links, asynchronous jobs with signed webhooks, bulk capture of up to 100 URLs per call, usage data and the OpenAPI specification.
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}`);
An MCP server supplies take_screenshot, get_page_info and capture_pdf tools to Claude, Cursor and other MCP clients. Plans include 1,000 screenshots per month free with no card, Starter at $5 for 3,000, Growth at $15 for 15,000, Pro at $39 for 60,000, Scale at $99 for 250,000 and Business at $249 for 1,000,000; yearly billing gives two months free, and every feature is on every plan. Sign up free for 1,000 screenshots a month with no card.
Frequently Asked Questions
Can Selenium take a screenshot before quitting the driver?
Yes. Capture while the session is active, then quit it in cleanup; after quitting, the browsing context no longer exists.
Does an element screenshot include content outside the element?
No. It targets the located WebElement, subject to the browser and driver’s supported element-screenshot behavior.
The Tool Desk
Outbyte Driver Updater FREEFix the driver behind crashes, sound loss and screen glitchesFind Drivers →Outbyte PC Repair FREERepair Windows errors before they cause bigger problemsFix Now →Where should screenshots be stored in CI?
Use a job artifact directory with unique, descriptive names, then configure the CI system to upload that directory after the test finishes.
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.

