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

In Selenium Python, call driver.get_screenshot_as_base64(). It returns a Base64-encoded screenshot of the current window as a string:

image_b64 = driver.get_screenshot_as_base64()

Use element.screenshot_as_base64 when you need one element instead of the current window.

Capture the current window as Base64 in Python

The Selenium Python API method is get_screenshot_as_base64(). It captures the current window and returns text, not a file path and not a bytes object. Capture after navigating to the page and after the page has reached the state you want to test or display.

from selenium import webdriver

# Configure the driver according to your Selenium installation.
driver = webdriver.Chrome()

try:
    driver.get("https://example.com")
    image_b64 = driver.get_screenshot_as_base64()
    print(image_b64[:80])
finally:
    driver.quit()

The printed value is only the beginning of the encoded image. Keep the complete string when writing it to a response, storing it, or embedding it.

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

Do not assume the method adds an HTML data-URL prefix

The API description says the result is a Base64-encoded screenshot. It does not promise that the returned string already begins with data:image/png;base64,. If an HTML consumer requires a data URL, add the prefix yourself:

data_url = "data:image/png;base64," + image_b64

This prefix is an application-level construction based on the documented PNG output. Treat image_b64 itself as the canonical Selenium result.

Choose the output that matches the next step

Selenium exposes several screenshot forms. Select the one that avoids an unnecessary conversion.

Need Python API Result
Current window for HTML or text transport driver.get_screenshot_as_base64() Base64 string
Current window for image processing driver.get_screenshot_as_png() PNG bytes
Current window saved as an artifact driver.save_screenshot("screenshot.png") or driver.get_screenshot_as_file("screenshot.png") PNG file; the file methods document a Boolean result and a filename ending in .png
One element for HTML or transport element.screenshot_as_base64 Base64 string for that element

The Python implementation of get_screenshot_as_png() decodes the Base64 screenshot into bytes. Therefore, use the bytes method when a library expects binary image data, rather than decoding the text yourself.

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.

Capture one element as Base64

Element screenshots use the element property, not the driver method. Locate the element first, then read screenshot_as_base64:

from selenium import webdriver

 driver = webdriver.Chrome()
try:
    driver.get("https://example.com")
    card = driver.find_element("css selector", ".product-card")
    card_b64 = card.screenshot_as_base64
    data_url = "data:image/png;base64," + card_b64
finally:
    driver.quit()

Replace .product-card with a selector that identifies the component you want. An element capture is useful for a visual regression fixture, a support attachment, or an image embedded in a generated report. It does not change the driver-level method: the driver method remains for the current window.

Practical Base64 handling patterns

Decode the string to a PNG file

If an API or queue gives you only the Base64 text, decode it before writing the image. Python’s standard library handles this without another Selenium call:

import base64

with open("screenshot.png", "wb") as output:
    output.write(base64.b64decode(image_b64))

Do not decode a string that still contains a data-URL header. If your input may be either form, remove everything through the first comma before calling b64decode.

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

Embed the image in generated HTML

For an inline image, construct the data URL and place it in an img element. Escape the value through your normal HTML templating system when the surrounding document is built:

html = f'<img alt="Selenium screenshot" src="{data_url}">'

The encoded image remains part of the HTML document, so the document can be self-contained. For large screenshots, a file or object-storage URL can be more practical than repeating the full Base64 value in markup.

Send it in JSON

A Base64 string is ordinary text and can be placed in a JSON field:

payload = {"screenshot_base64": image_b64}

Use your JSON library to serialize the object. Do not manually add quoting or line breaks; serializers preserve the encoded value safely.

Free tools Windows power users keep installed

One-click scans. No signup required.

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

A complete capture sequence for dynamic pages

The screenshot records the browser state at the instant the method runs. If the page fills in content with JavaScript, perform the navigation and any required interaction before reading the value. A typical sequence is:

  1. Start the WebDriver instance.
  2. Navigate with driver.get().
  3. Wait for the page condition your test cares about, such as a result element being present.
  4. Perform clicks, scrolling, or form entry needed to create the desired state.
  5. Call get_screenshot_as_base64() for the window or screenshot_as_base64 for one element.
  6. Persist, embed, or transmit the result before quitting the driver.

Selenium’s documented driver method targets the current window. Do not describe it as a guaranteed full-page capture: the API reference supplied for this method establishes the current-window result, not a cross-browser full-page standard. If your test needs content below the viewport, scroll or use a capture approach designed for that requirement and verify the resulting scope in your own browser/driver combination.

Java: request Base64 through TakesScreenshot

In Java, the equivalent is the TakesScreenshot interface with OutputType.BASE64:

import org.openqa.selenium.OutputType;
import org.openqa.selenium.TakesScreenshot;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;

public class Base64Shot {
    public static void main(String[] args) {
        WebDriver driver = new ChromeDriver();
        try {
            driver.get("https://example.com");
            String imageB64 = ((TakesScreenshot) driver)
                    .getScreenshotAs(OutputType.BASE64);
            System.out.println(imageB64.substring(0, Math.min(80, imageB64.length())));
        } finally {
            driver.quit();
        }
    }
}

The Java API documentation describes screenshot capture for W3C-conformant WebDriver and WebElement implementations. For a non-conformant implementation it makes a best effort, so do not promise identical scope or pixels across every browser-driver combination.

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

Timing, scope, and compatibility checks

Capture the state you intend to show

A fast call can still capture an intermediate state: a loading skeleton, an open menu, or a page before images finish rendering. Wait for a meaningful condition rather than relying only on a fixed sleep. The condition should be specific to your page, such as the presence of the component whose screenshot you are about to take.

Keep window and element targets distinct

Use the driver method when the required artifact is the current browser window. Use the element property when a selector identifies the exact component. Calling the driver method does not automatically narrow the result to the last element you found.

Check your Selenium and driver setup

The referenced Python API documentation identifies Selenium 4.49.0. Your installed Selenium package, browser, and WebDriver must be compatible with one another. The documented method signatures establish the API; they do not provide a browser/version compatibility matrix or a guarantee for every implementation.

Troubleshooting

AttributeError for get_screenshot_as_base64

Confirm that the object is a Selenium WebDriver instance and that the method name is spelled exactly, including all underscores. If you intended an element capture, the API is the property element.screenshot_as_base64, without parentheses. Also verify that your Selenium package is current enough to expose the documented API.

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

The output cannot be opened as an image

Make sure you retained the complete Base64 string and decoded it as Base64, not as hexadecimal or plain text. If you created a data URL, use the correct PNG media prefix and do not pass the prefix itself to a decoder unless you first remove it. Saving the value directly with text encoding produces an encoded text file, not a PNG.

The screenshot shows a loading or incomplete page

Move the capture after the page-specific readiness condition. For a lazy-rendered section, scroll or otherwise trigger the section before capturing. A screenshot call does not wait for every application-specific network request unless your test explicitly waits for the state you need.

The element property fails or captures the wrong region

Check that the selector resolves to the intended element at capture time. A re-render can replace the node between lookup and capture; locate it again after the page settles. If several elements match, make the selector more specific instead of assuming the first match is correct.

The Java call is unsupported

Ensure the driver can be cast to TakesScreenshot and that you request OutputType.BASE64. If the implementation is not W3C-conformant, Selenium documents the result as best effort rather than identical across implementations.

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

The Base64 payload is too large for the destination

Base64 is text, so it can be substantially larger than the underlying binary image. For queues, logs, or database columns with strict limits, use PNG bytes or a file method instead, or store the file and transmit a reference. Avoid logging the full value in routine test output.

Performance and reliability considerations

  • Choose the cheapest conversion path. Use the Base64 method when the next system accepts text, the PNG method when it accepts bytes, and a file method when a test runner already collects files.
  • Capture only what you need. An element screenshot can reduce the artifact and makes visual assertions more focused than a whole-window image.
  • Control lifecycle. Take the screenshot before driver.quit(), and close the driver in a finally block so failed tests do not leave browser processes running.
  • Make readiness explicit. Deterministic waits improve repeatability more than adding arbitrary delays, because the screenshot is tied to the actual page state.
  • Treat output as sensitive. Screenshots can contain account data, tokens displayed in a page, or personal information. Apply the same access controls to Base64 strings as to PNG files.
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 clean website capture rather than Selenium control, ScreenshotNeo provides a single HTTP request. Its API accepts the cookie or consent banner like a visitor and removes more than 60 known consent platforms, newsletter popups, and chat widgets before capture; each step can be disabled. Only clean shots are billed, while bot checks or CAPTCHAs, blank pages, timeouts, failed loads, and cache hits cost nothing. The response identifies the page verdict and billing result in X-Page-Verdict and X-Billed headers.

See the ScreenshotNeo API documentation for parameters and response details. A direct cURL 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 same request in Python is:

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)

And in 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 also offers an MCP server with take_screenshot, get_page_info, and capture_pdf tools for Claude, Cursor, and other MCP clients. It supports PNG, JPEG, WebP, and PDF output, plus options such as full-page capture with lazy images loaded, CSS-selector element capture, device presets, custom CSS or JavaScript, waits, request blocking, headers and cookies, geolocation, caching, signed links, asynchronous jobs, bulk capture, and a usage API.

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

The Free plan includes 1,000 screenshots each month with no card; paid plans start at $5 for 3,000 screenshots, and every feature is available on every plan. Create a free ScreenshotNeo account to try the API.

FAQ

Does a Selenium Base64 screenshot create a public image URL?

No. The method returns encoded image content. Making it publicly addressable requires your own storage or delivery layer; the Selenium API does not publish a URL for the result.

Can I include the encoded value in a test report without writing a file?

Yes. Keep the returned string in memory, construct a data URL when the report uses an HTML img element, and let the report generator escape the value as it serializes the document.

What should I record when a visual test fails?

Record the target type (window or element), the page state or readiness condition used, and the browser-driver combination. Those details distinguish a genuinely changed page from a capture taken before the UI finished rendering.

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

Frequently Asked Questions

Does a Selenium Base64 screenshot create a public image URL?

No. The method returns encoded image content. Making it publicly addressable requires your own storage or delivery layer; Selenium does not publish a URL for the result.

Can I include the encoded value in a test report without writing a file?

Yes. Keep the string in memory, construct a data URL for an HTML image, and let your report generator escape it during serialization.

What should I record when a visual test fails?

Record whether the target was the window or an element, which readiness condition ran, and the browser-driver combination.

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.