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 return-value screenshot methods instead of its file-saving methods. In Python, driver.get_screenshot_as_png() gives you PNG bytes and driver.get_screenshot_as_base64() gives you a Base64 string. In Java, getScreenshotAs(OutputType.BYTES) and getScreenshotAs(OutputType.BASE64) provide the same choices. The image stays in your process until you pass it to an encoder, test report, HTTP client, object store, or other consumer.

Choose the in-memory representation first

Your downstream code determines the best return type:

Need Use Result
Image processing, multipart upload, hashing, or binary storage PNG bytes Binary data in memory
HTML or JSON that expects text Base64 Encoded string
A durable artifact on disk save_screenshot() or a file output type File (not an in-memory-only workflow)

Returning bytes or Base64 avoids an intermediate screenshot file. It does not make the capture asynchronous or guarantee that the page is fully rendered; you still control navigation, waits, and the browser state before calling the method.

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.

Python: capture PNG bytes without a file

Minimal example

from selenium import webdriver

 driver = webdriver.Chrome()
 try:
     driver.get("https://example.com")
     png_bytes = driver.get_screenshot_as_png()
     print(f"Captured {len(png_bytes)} bytes")
 finally:
     driver.quit()

png_bytes is a Python bytes object containing a PNG image. Pass it directly to code that accepts binary data. For example, Pillow can decode it through an in-memory stream:

#1 Best Overall
Sale
Philips 24 Inch Computer Monitor FHD 100Hz VA VESA Flicker-Free, 241V8LB
  • CRISP CLARITY: This 23.8″ Philips V line monitor delivers crisp Full HD 1920x1080 visuals. Enjoy movies, shows and videos with remarkable detail
  • INCREDIBLE CONTRAST: The VA panel produces brighter whites and deeper blacks. You get true-to-life images and more gradients with 16.7 million colors
  • THE PERFECT VIEW: The 178/178 degree extra wide viewing angle prevents the shifting of colors when viewed from an offset angle, so you always get consistent colors
  • WORK SEAMLESSLY: This sleek monitor is virtually bezel-free on three sides, so the screen looks even bigger for the viewer. This minimalistic design also allows for seamless multi-monitor setups that enhance your workflow and boost productivity
  • A BETTER READING EXPERIENCE: For busy office workers, EasyRead mode provides a more paper-like experience for when viewing lengthy documents
from io import BytesIO
from PIL import Image

png_bytes = driver.get_screenshot_as_png()
image = Image.open(BytesIO(png_bytes))
print(image.size, image.mode)

No screenshot file is created by get_screenshot_as_png(). Keep the driver open until the call completes, and close it in a finally block so browser processes are not left behind when capture fails.

Get Base64 for HTML or text-only transports

image_base64 = driver.get_screenshot_as_base64()
html = f'<img alt="Selenium capture" src="data:image/png;base64,{image_base64}">'

Selenium documents this Base64 form as useful for embedding a screenshot in HTML. The returned value is text, so it is convenient for a report template or a JSON payload that cannot carry raw bytes. Add the data:image/png;base64, prefix only when the receiving format expects a data URL; the Selenium value itself is the encoded image data.

Persist only when the consumer requires a file

driver.save_screenshot("screenshot.png")
# or
ok = driver.get_screenshot_as_file("screenshot.png")
if not ok:
    raise IOError("Selenium could not write the screenshot")

save_screenshot() and get_screenshot_as_file() are separate file-writing APIs. The latter returns False on an I/O error and True otherwise. Do not call one of them merely to read the image back into memory; use get_screenshot_as_png() instead.

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

Java: select BYTES or BASE64 with OutputType

Raw bytes

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");
    byte[] pngBytes = ((TakesScreenshot) driver)
        .getScreenshotAs(OutputType.BYTES);
    System.out.println("Captured " + pngBytes.length + " bytes");
} finally {
    driver.quit();
}

The cast expresses the Selenium capability being used: the driver must implement TakesScreenshot. OutputType.BYTES returns the PNG as a byte array, which can be handed to an image library, a multipart request, or a database driver without creating a temporary path.

Rank #2
Philips 22 Inch Computer Monitor FHD 100Hz VA VESA Flicker-Free, 221V8LB
  • CRISP CLARITY: This 22 inch class (21.5″ viewable) Philips V line monitor delivers crisp Full HD 1920x1080 visuals. Enjoy movies, shows and videos with remarkable detail
  • 100HZ FAST REFRESH RATE: 100Hz brings your favorite movies and video games to life. Stream, binge, and play effortlessly
  • SMOOTH ACTION WITH ADAPTIVE-SYNC: Adaptive-Sync technology ensures fluid action sequences and rapid response time. Every frame will be rendered smoothly with crystal clarity and without stutter
  • INCREDIBLE CONTRAST: The VA panel produces brighter whites and deeper blacks. You get true-to-life images and more gradients with 16.7 million colors
  • THE PERFECT VIEW: The 178/178 degree extra wide viewing angle prevents the shifting of colors when viewed from an offset angle, so you always get consistent colors

Base64 text

String base64 = ((TakesScreenshot) driver)
    .getScreenshotAs(OutputType.BASE64);
String imgTag = "<img alt="Capture" src="data:image/png;base64,"
    + base64 + "">";

Use BASE64 when the receiving API or report is text-oriented. OutputType.FILE is the alternative when a temporary file is explicitly required; Selenium’s Java API documents that this temporary file is deleted when the JVM exits, so copy it to durable storage if you need it after the process ends.

Handle Java failure modes

A screenshot call can throw WebDriverException when the driver reports a capture failure. An implementation can also throw UnsupportedOperationException when screenshot capture is not supported. Catch these at the boundary where you can add the URL, browser, and test name to your diagnostic log, then decide whether the test should fail or continue.

JavaScript: keep the encoded result in memory

Selenium’s JavaScript binding exposes takeScreenshot(), which returns an encoded screenshot string for the current browsing context:

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
const { Builder } = require('selenium-webdriver');

(async function capture() {
  const driver = await new Builder().forBrowser('chrome').build();
  try {
    await driver.get('https://example.com');
    const base64 = await driver.takeScreenshot();
    console.log(`Captured ${base64.length} Base64 characters`);
    // Send `base64` to a report or decode it only at the final boundary.
  } finally {
    await driver.quit();
  }
})();

If a receiving API needs binary data, decode the Base64 string at that boundary rather than writing a temporary screenshot first. The exact return and file-writing conveniences vary by Selenium binding; check the version of the binding installed in your project.

Rank #3
Sale
Dell 24 Monitor - SE2426H - 23.8-inch FHD (1920x1080) 144Hz 1ms Display, in-Plane Switching (IPS) Technology, AMD FreeSync™, TÜV 3-Star 2X HDMI, Tilt
  • Clear visuals. Fluid motion: A 144Hz refresh rate and 1ms MPRT deliver smooth, tear‑free motion across work, gaming, and streaming for clearer, more fluid viewing.
  • Eye comfort: TÜV Rheinland 3‑star* certification reduces harmful blue light while preserving stunning color quality without compromise. *TÜV Rheinland 3-star eye comfort certification.
  • Wide viewing angle: Get consistent views across a wide 178° /178° viewing angle.
  • In-Plane Switching (IPS): See excellent color accuracy and consistency across wide viewing angles with In-plane Switching (IPS) technology.
  • Ultra-thin bezels: Maximize your viewing experience with thin bezels.

Capture the intended state, not merely the current URL

Wait for an application condition

Call the screenshot method after navigation and the UI updates that your test is meant to document. Prefer a condition that represents readiness—such as a result element becoming visible—over an arbitrary sleep. Selenium does not provide a universal wait interval that guarantees asynchronous content has finished rendering, so the condition belongs in your test’s application-specific logic.

from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC

WebDriverWait(driver, 15).until(
    EC.visibility_of_element_located((By.CSS_SELECTOR, "main"))
)
png_bytes = driver.get_screenshot_as_png()

Know what the screenshot scope means

Treat a generic WebDriver screenshot as a capture of the current browsing context or window. A W3C-conformant driver follows WebDriver screenshot behavior, while a non-conformant implementation may return the whole page, the current window, or only a visible frame area. Do not label the result “full page” unless the specific browser and driver document and support that capability. A screenshot of a WebElement, where supported by your binding, is a different operation from a window screenshot.

Frames and windows

If the target is inside an iframe, switch into that frame before waiting for its element and capturing. Likewise, switch to the intended tab or window handle; Selenium captures the current browsing context, not every open tab.

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

Use the bytes safely in real pipelines

Upload without a temporary path

import requests

png_bytes = driver.get_screenshot_as_png()
response = requests.post(
    "https://upload.example.test/artifacts",
    files={"file": ("capture.png", png_bytes, "image/png")},
    timeout=30,
)
response.raise_for_status()

Keep the content type consistent with the returned format: Selenium’s standard screenshot output is PNG. If you retain many captures, release references after upload or report generation; in-memory images still consume process memory until garbage-collected.

Rank #4
Samsung 27" Essential S3 (S36GD) Series FHD 1800R Curved Computer Monitor
  • CURVED FOR ENHANCED ENGAGEMENT: An immersive viewing experience with a curved monitor that wraps more closely around your field of vision; It creates a wider view, enhancing depth perception and minimizing peripheral distraction
  • SMOOTH PERFORMANCE FOR SEAMLESS CONTENT: Stay in the action when playing games, watching videos, or working on creative projects; The 100Hz refresh rate reduces lag and motion blur so you don't miss a thing in fast-paced moments¹
  • MORE GAMING POWER: Gain the edge with optimizable game settings; Color and image contrast can be adjusted to see scenes more vividly and spot enemies hiding in the dark; Game Mode adjusts any game to fill the screen so you can view every detail²
  • KEEP IT EASY ON THE EYES: Care for your eyes and stay comfortable, even during long sessions; Advanced eye comfort technology certified by TÜV reduces eye strain by minimizing blue light and reducing irritating screen flicker²
  • INCREASED VERSATILITY: Connect to more; Plug devices straight into your monitor for increased flexibility, making your computing environment even more convenient

Embed in a test report

For an HTML report, Base64 makes the artifact self-contained, but it increases the text payload compared with raw bytes. For a binary artifact store, send the bytes directly. The available documentation establishes the formats, not a universal speed or memory-footprint winner, so choose according to the receiving interface and measure your own workload if volume matters.

Common errors and fixes

Symptom Likely cause Fix
AttributeError for a screenshot method Wrong binding, object, or an outdated wrapper Call the method on the Selenium WebDriver instance and verify the installed binding version.
Java ClassCastException The driver object does not implement TakesScreenshot Use a driver that supports the capability and cast it to TakesScreenshot only at the call site.
UnsupportedOperationException The implementation does not support screenshots Use a supported browser/driver combination or skip the capture with an explicit test diagnostic.
WebDriverException or a blank result Driver/browser failure, a page that has not reached the intended state, or an unsupported capture scope Check driver logs, wait for a meaningful UI condition, confirm the active window/frame, and retry only when a retry is semantically safe.
Base64 image does not render Missing data-URL prefix or incorrect MIME type Use data:image/png;base64, before the returned Base64 value when embedding in an img tag.
Expected full page, received viewport Generic screenshot behavior is implementation-dependent Use a documented full-page feature for your browser/driver, or redesign the evidence around a viewport or element capture.
File API returns False Path permissions or another I/O error Check the directory and permissions, or avoid disk output and use the bytes API.
Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.Support on Ko-Fi

Or skip the browser setup

If you only need a website image rather than an interactive Selenium session, ScreenshotNeo returns a screenshot from one HTTP request. It accepts consent banners like a visitor and removes more than 60 known consent platforms, newsletter popups, and chat widgets before capture; each cleanup step can be disabled. Bot checks or CAPTCHAs, blank pages, timeouts, failed loads, and cache hits are not billed, and response headers report the page verdict and billing status.

Its API supports PNG, JPEG, WebP, and PDF output, plus full-page lazy-image loading, CSS-selector element capture, dark mode, device presets or custom viewports, retina scale, custom CSS and JavaScript, clicks, selector or network-idle waits, request/resource blocking, headers, cookies, user agents, Authorization, timezone, geolocation, transparent backgrounds, resizing, configurable-TTL caching, signed image links, asynchronous jobs with signed webhooks, bulk capture of up to 100 URLs per call, a usage API, and an OpenAPI specification. An MCP server exposes take_screenshot, get_page_info, and capture_pdf to Claude, Cursor, and other MCP clients.

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

See the ScreenshotNeo documentation for parameters and authentication. A minimal request is:

curl -G "https://api.screenshotneo.com/v1/shot" -d access_key=YOUR_API_KEY --data-urlencode url=https://stripe.com -o shot.webp

The free plan includes 1,000 screenshots per month with no card. Paid plans start at $5 for 3,000 shots; every feature is available on every plan, and yearly billing gives two months free. Create a free ScreenshotNeo account to get an API key.

Best Value
Sale
Sceptre New 22-Inch Gaming Monitor, FHD 1080p, Up to 144Hz, HDMI, DisplayPort, Built-in Speakers, Machine Black (E225W-FW144 Series, 2026)
  • 【INTEGRATED SPEAKERS】Whether you're at work or in the midst of an intense gaming session, our built-in speakers provide rich and seamless audio, all while keeping your desk clutter-free.
  • 【EASY ON THE EYES】 Protect your eyes and enhance your comfort with Blue-Light Shift technology. This feature reduces harmful blue light emissions from your screen, helping to alleviate eye strain during long hours of use and promoting healthier viewing habits.
  • 【WIDEN YOUR PERSPECTIVE】Our sleek minimal bezel design ensures undivided attention. The nearly bezel-free display seamlessly connects in a dual monitor arrangement, delivering an unobstructed view that lets you focus on more at once, completely distraction-free.

Operational and cost considerations

  • Memory: each in-memory image remains allocated while referenced. Process or upload captures promptly in large suites.
  • Reliability: record the browser, driver, URL, active window/frame, and readiness condition with failures so a blank or partial capture is diagnosable.
  • Portability: verify screenshot support and scope for the exact browser, driver, and Selenium binding versions in your build.
  • Billing: Selenium itself does not impose a screenshot-service charge; any storage, report, or external API cost comes from your surrounding pipeline. ScreenshotNeo bills only clean shots and identifies verdict and billing in headers.

FAQ

Does an in-memory screenshot have to be PNG?

The Selenium methods described here return PNG screenshot data. Convert it after capture if your downstream pipeline requires another image format.

Can I capture before calling quit()?

Yes. Capture while the driver session and target browsing context are still active, then close the driver in cleanup code.

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

Will returned bytes include browser chrome?

The screenshot represents the WebDriver browsing context, not the operating-system browser frame or desktop chrome.

Frequently Asked Questions

Which Python method should I use for an API upload?

Use get_screenshot_as_png() when the upload accepts binary bytes; use get_screenshot_as_base64() when it accepts text.

Why is my Selenium screenshot not full-page?

A generic screenshot’s scope depends on the WebDriver implementation. Confirm whether your browser and driver document full-page capture instead of assuming it.

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.

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