In Python, call driver.save_screenshot("artifacts/example.png") after navigating to the page; in Java, use TakesScreenshot with OutputType.FILE. Both examples below save a PNG of the current browser window. Create the destination directory first, check that the save succeeded, and call driver.quit() even if capture fails. A full-document screenshot is a separate, driver-specific capability.
Save the current browser window as a PNG in Python
Selenium’s Python API describes save_screenshot(filename) as saving the current window to a PNG image file. It returns a Boolean: False indicates an I/O error. The following example creates its output directory, checks that return value, and closes the browser in a finally block so the browser is quit whether capture succeeds or raises an error.
from pathlib import Path
from selenium import webdriver
out = Path("artifacts")
out.mkdir(parents=True, exist_ok=True)
driver = webdriver.Chrome()
try:
driver.get("https://example.com")
screenshot_path = out / "example.png"
ok = driver.save_screenshot(str(screenshot_path))
if not ok:
raise OSError(f"Selenium could not write the screenshot: {screenshot_path}")
finally:
driver.quit()
Run this in a Python environment where Selenium and the Chrome browser/driver setup are already available. The relative path artifacts/example.png is resolved from the process’s current working directory, not necessarily from the directory containing the script. Change the path if you want the image somewhere else.
get_screenshot_as_file(filename) is another file-oriented Python method for the same kind of PNG capture; its documented filename should end in .png. Prefer an explicit PNG extension so the filename reflects the output format. Check the Boolean result rather than assuming that a method call necessarily produced a usable file.
Do these 3 things before closing this tab:
1Clear out junk files and repair common Windows errors2Scan for outdated or missing drivers - takes under a minute3Repair Windows errors before they cause bigger problems#1 Best Overall
- Record videos and take screenshots of your computer screen including sound
- Highlight the movement of your mouse
- Record your webcam and insert it into your screen video
- Edit your recording easily
- Perfect for video tutorials, gaming videos, online classes and more
Keep the PNG in memory instead of writing a file
If the next step in your program consumes image data directly, use get_screenshot_as_png() to get PNG bytes. If you need a Base64 string, use get_screenshot_as_base64(); Selenium documents it as useful for embedding in HTML. These methods avoid choosing a destination filename, but they do not change the capture scope: the regular screenshot is still the current browser window.
png_bytes = driver.get_screenshot_as_png()
base64_png = driver.get_screenshot_as_base64()
Keep the output forms distinct in your code: the first value is bytes, the second is a Base64-encoded string, and save_screenshot writes a PNG file and returns a success indicator. Do not treat Base64 text as if it were the PNG file’s raw bytes.
Save a screenshot as a file in Java
In Java, the screenshot interface is TakesScreenshot. Its getScreenshotAs(OutputType<X>) method supports different output forms, including FILE and BASE64. This runnable example creates the target directory and copies the temporary screenshot file to a predictable path.
import java.io.File;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.StandardCopyOption;
import org.openqa.selenium.OutputType;
import org.openqa.selenium.TakesScreenshot;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
public class ScreenshotExample {
public static void main(String[] args) throws Exception {
Path outputDir = Path.of("artifacts");
Files.createDirectories(outputDir);
WebDriver driver = new ChromeDriver();
try {
driver.get("https://example.com");
File source = ((TakesScreenshot) driver)
.getScreenshotAs(OutputType.FILE);
Path destination = outputDir.resolve("example.png");
Files.copy(source.toPath(), destination,
StandardCopyOption.REPLACE_EXISTING);
} finally {
driver.quit();
}
}
}
The Java API’s screenshot contract applies to drivers and to WebElement objects that implement TakesScreenshot. A driver screenshot and an element screenshot answer different questions: the former captures the current browser context, while the latter is for a particular element. Support depends on the object implementing the screenshot interface.
The Tool Desk
Outbyte PC Repair FREERepair Windows errors before they cause bigger problemsFix Now →Outbyte Driver Updater FREEScan for outdated or missing drivers - takes under a minuteDriver Scan →Rank #2
- Mix an audio, music and voice tracks
- Record single or multiple tracks simultaneously
- Intuitive tools to split, trim, join, and many other editing features
- Loaded with audio effects including EQ, compression, reverb, and more.
- Load an audio file and export to all popular audio formats from studio quality wav to high compression formats
Capture one element instead of the browser window
When the image should contain one element rather than the browser context, use the screenshot method on the element, provided the language binding and driver expose that capability. In Java, the documented TakesScreenshot interface includes WebElement as a subinterface, so an element implementing it can be requested as a file:
WebElement element = driver.findElement(By.cssSelector("main"));
File source = ((TakesScreenshot) element).getScreenshotAs(OutputType.FILE);
Files.copy(source.toPath(), Path.of("artifacts", "main.png"),
StandardCopyOption.REPLACE_EXISTING);
This snippet assumes driver has already opened the target page, the element has been located, and artifacts exists. Add the corresponding imports for WebElement, By, File, Files, Path, StandardCopyOption, TakesScreenshot, and OutputType in a standalone class. If the driver or element does not implement the screenshot interface, this approach is not available for that object.
Capture the full page when the driver supports it
A normal save_screenshot call is documented as a screenshot of the current window; it should not be described as a universal full-document capture. Full-page capture is a distinct capability and behavior varies by driver. For example, Firefox’s Python WebDriver API documents get_full_page_screenshot_as_file("artifacts/full.png") for capturing the full document.
from pathlib import Path
from selenium import webdriver
out = Path("artifacts")
out.mkdir(parents=True, exist_ok=True)
driver = webdriver.Firefox()
try:
driver.get("https://example.com")
ok = driver.get_full_page_screenshot_as_file(str(out / "full.png"))
if not ok:
raise OSError("Selenium could not write the full-page screenshot")
finally:
driver.quit()
Use this method specifically with Firefox’s documented Python API; do not assume the same method or full-page behavior exists for every browser driver or language binding. If the output is unexpectedly limited to the visible window, first confirm that you are calling a full-page method supported by the driver rather than the regular window screenshot method.
Rank #3
Choose the capture scope and output form
| Need | Approach | Output or scope | Important qualification |
|---|---|---|---|
| Save what is currently shown in the browser window | Python save_screenshot or get_screenshot_as_file |
PNG file | File-oriented Python calls expect a PNG filename; the Boolean result indicates success. |
| Use image data directly in a Python program | get_screenshot_as_png |
PNG bytes | Returns bytes rather than a saved file. |
| Embed a screenshot as encoded text | get_screenshot_as_base64 in Python, or Java OutputType.BASE64 |
Base64 | Base64 is encoded data, not a path to a PNG file. |
| Save a Java driver screenshot | TakesScreenshot with OutputType.FILE |
File | Copy the returned file to the destination you want to keep. |
| Capture one page element | Element screenshot method where the element implements TakesScreenshot |
Element capture | Availability depends on the element and driver implementing the interface. |
| Capture the full document | Use a driver-specific full-page method, such as Firefox Python’s get_full_page_screenshot_as_file |
Full-page PNG file | Full-page behavior is not identical across drivers. |
The official Selenium Python API documents the Python method behavior, and the Selenium Java API documents TakesScreenshot and its output types. The Firefox Python WebDriver API separately documents its full-page method. Those distinctions matter more than the filename: a PNG extension does not turn a current-window capture into a full-page capture.
Troubleshoot missing or unusable screenshots
The output file is missing
- Create the parent directory. The examples create
artifactsbefore saving. If the destination path includes a directory that does not exist, create it before the screenshot call. - Check the path you are writing. A relative path is based on the running process’s working directory. Use an absolute path or inspect the working directory if you are looking in a different folder than expected.
- Check the method result. In Python, both documented file-oriented screenshot methods return a Boolean success indicator. Treat
Falseas a failed write and handle it instead of silently continuing.
The file is not a PNG or cannot be used where expected
- Use a
.pngfilename for Python’s file methods. The documented file-oriented operation is PNG output and specifies a filename ending in.png. - Match the output type to the next step. Use PNG bytes for code that consumes bytes, Base64 for an HTML embedding workflow, and a file output when a saved image is needed.
- Do not confuse the source file in Java with the final destination.
OutputType.FILEgives you a file to copy; copy it to the path your application expects.
The screenshot does not include the whole page or the desired element
- Verify the requested scope. The regular Python screenshot is the current window. A full document needs a distinct driver-supported method.
- Use an element capture only when supported. The Java contract covers
WebElementobjects that implementTakesScreenshot; it does not establish that every driver supports every element capture. - Check the browser and binding combination. The documented full-page Python method cited here is specific to Firefox. Do not infer identical support for another driver from that example.
The browser stays open after an error
Put navigation and screenshot work inside try and call driver.quit() in finally. That ensures cleanup is attempted whether the screenshot succeeds, the save reports failure, or another operation raises an exception. In Java, use the same try/finally pattern around the driver lifetime.
Performance, reliability, and cost considerations
The Selenium API references described here do not publish a stable capture-time, success-rate, or image-quality figure. Actual runtime depends on the browser and page work your script performs, so do not treat a single observed duration as a general benchmark. Selenium is useful when the task already involves controlling a browser and needs a window, element, or driver-specific full-page capture. The screenshot calls themselves do not establish that a page has reached the state your workflow requires; structure navigation and any application-specific readiness checks separately.
For reliability, make output handling explicit: create the directory, select the right capture scope, verify the file-oriented Python result, and close the driver in cleanup code. For cost, Selenium itself does not supply a per-screenshot billing model in the API guidance here; browser execution and the environment used to run it are separate considerations. If the requirement is simply to request a screenshot of a URL without setting up a browser workflow, a screenshot API is a different option.
What’s actually slowing this PC down?
Pick the symptom - the matching free tool is one click away.
Rank #4
- Transform audio playing via your speakers and headphones
- Improve sound quality by adjusting it with effects
- Take control over the sound playing through audio hardware
Or skip the browser setup
ScreenshotNeo is a website screenshot API and MCP server: one GET request with a URL can return a PNG, JPEG, WebP, or PDF. Its clean-shot options accept cookie or consent banners like a visitor and remove more than 60 known consent platforms, newsletter popups, and chat widgets before capture; each of those steps can be turned off. Only clean shots are billed: bot checks or CAPTCHAs, blank pages, timeouts, failed loads, and cache hits cost nothing, and responses identify the page verdict and billing status in headers. Its MCP server offers take_screenshot, get_page_info, and capture_pdf to Claude, Cursor, and other MCP clients.
For a one-request screenshot, use cURL (replace the example 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
See the ScreenshotNeo API documentation for request options. The same endpoint can be called from 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)
Or from 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}`);
ScreenshotNeo offers 1,000 shots per month free without a card. Paid plans start at $5 for 3,000 shots; every feature is available on every plan. If you need Selenium’s browser automation, element capture, or driver-specific behavior, keep the Selenium approach above; an API call is an alternative for URL-based captures, not a replacement for every browser-control task. Sign up for 1,000 free screenshots a month, with no card required.
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 →Frequently Asked Questions
Can Selenium return a screenshot without saving it to disk?
Yes. In Python, use get_screenshot_as_png() for PNG bytes or get_screenshot_as_base64() for a Base64 string. In Java, TakesScreenshot supports output types including BASE64.
Does a regular Selenium screenshot capture the full page?
Not necessarily. The regular Python file method is documented for the current window. Full-page capture is driver-specific; Firefox’s Python API documents a separate full-page method.
Can I save a Selenium screenshot in JPEG or WebP?
The Selenium file methods covered here are documented as PNG output. The ScreenshotNeo endpoint, by contrast, can return PNG, JPEG, WebP, or PDF.
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.

