ScreenshotNeo

BlogHow-to

How to Return a Selenium Screenshot as a Base64 String

Use Selenium’s screenshot API to get a Base64 string, embed it in HTML, or choose PNG bytes or a file when that better fits your workflow.

By the ScreenshotNeo team4 October 20266 min read

In Python, call driver.get_screenshot_as_base64() on an active Selenium WebDriver session. It returns a Base64-encoded PNG payload as a Python str; it does not return PNG bytes or a complete data URL. Selenium documents the method for the current window. Python WebDriver API

from selenium import webdriver

 driver = webdriver.Chrome()
try:
    driver.get("https://example.com")
    screenshot_b64 = driver.get_screenshot_as_base64()
    print(screenshot_b64[:80])  # Base64 text, not raw PNG bytes
finally:
    driver.quit()

The example assumes Selenium and a compatible browser driver are installed and configured. See Selenium’s official documentation for setup and binding-specific details.

1. Choose the representation you need

Base64 is an encoding of binary image data as text. Choose the screenshot method based on what consumes the result next:

What you need Python method Result
Text for an API, template, or transport get_screenshot_as_base64() Base64 string
Image processing in memory get_screenshot_as_png() PNG bytes
A PNG on disk save_screenshot(path) or get_screenshot_as_file(path) File; the file method returns a Boolean success value

These are different representations of the screenshot. Do not decode the Base64 string unless the next step needs raw bytes. Selenium’s Python API documents both Base64 and PNG methods, and the file API documents its save behavior. Selenium Python WebDriver API · PNG method reference

2. Embed the screenshot in HTML

An HTML image source needs a data URL. Add the PNG media type prefix to the Base64 payload:

from selenium import webdriver

 driver = webdriver.Chrome()
try:
    driver.get("https://example.com")
    screenshot_b64 = driver.get_screenshot_as_base64()
    img_src = f"data:image/png;base64,{screenshot_b64}"
    html = f'<img alt="Page screenshot" src="{img_src}">'
    print(html)
finally:
    driver.quit()

Use data:image/png;base64, only when the payload is a PNG and the consumer accepts data URLs. The Selenium method returns the encoded screenshot data, not this prefix.

3. Return Base64 from an HTTP endpoint

If another application calls your service, serialize the string as a JSON field. Keep the browser session lifecycle bounded and return an error response if capture fails. This minimal Flask example returns JSON:

from flask import Flask, jsonify
from selenium import webdriver

app = Flask(__name__)

@app.get("/screenshot")
def screenshot():
    driver = webdriver.Chrome()
    try:
        driver.get("https://example.com")
        return jsonify({"screenshot_base64": driver.get_screenshot_as_base64()})
    finally:
        driver.quit()

if __name__ == "__main__":
    app.run()

For a production service, manage browser concurrency, request timeouts, and cleanup explicitly. Base64 expands binary data when represented as text, so for large screenshots or frequent transfers consider whether your client can accept PNG bytes or a file instead.

4. Other Selenium language bindings

The method name and return type vary by binding. Selenium’s official documentation shows JavaScript’s driver.takeScreenshot() returning an encoded string, and the Java API supports OutputType.BASE64. Check the API reference for the binding and version in your project. Selenium documentation

JavaScript

const { Builder } = require('selenium-webdriver');
const fs = require('node:fs/promises');

(async () => {
  const driver = await new Builder().forBrowser('chrome').build();
  try {
    await driver.get('https://example.com');
    const screenshotBase64 = await driver.takeScreenshot();
    console.log(screenshotBase64.slice(0, 80));
    // If a file is needed, decode the Base64 string:
    await fs.writeFile('screenshot.png', Buffer.from(screenshotBase64, 'base64'));
  } finally {
    await driver.quit();
  }
})();

Java

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

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

The Java example follows Selenium’s TakesScreenshot API. Screenshot scope depends on the implementation and target. The Java reference describes best-effort behavior for nonconformant implementations; confirm the result in your chosen browser and driver.

5. Capture scope and output details

  • Current window: Python’s get_screenshot_as_base64() is documented as taking a screenshot of the current window.
  • Element: Use the relevant WebElement screenshot API when you need one element. Do not assume a driver screenshot is an element screenshot.
  • Full page: Do not assume the current-window method captures an arbitrarily long document in every browser. Verify the desired scope with your binding and browser.
  • String versus bytes: Keep Base64 as text for JSON or an HTML data URL. Decode only for binary image processing or file output.

Selenium’s documentation includes screenshot examples for multiple bindings and element-level use cases. Official screenshot documentation

6. Troubleshooting

Symptom Likely cause Fix
get_screenshot_as_base64 is missing The object is not a Python WebDriver, or the binding/API differs. Confirm the object and language binding, then use that binding’s screenshot API.
Browser or driver startup fails The browser, driver, or Selenium setup is unavailable or incompatible. Resolve browser-driver setup using Selenium’s official installation documentation before capturing.
Image shows an error or incomplete page Capture happened before navigation or page rendering completed. Wait for the page condition your application requires before calling the screenshot method.
HTML displays a broken image The raw Base64 was used without a data URL prefix, or the media type does not match. For PNG, use data:image/png;base64, followed by the unmodified payload.
Image processing rejects the value Base64 text was passed where raw image bytes were expected. Decode the Base64 only at that boundary; use get_screenshot_as_png() when Python PNG bytes are the desired result.
Capture is not the whole document The driver method captures the current window scope, not necessarily an arbitrarily long page. Use an appropriate full-page approach for your browser or capture the specific element; verify scope in your target setup.
Browser process remains after an exception Cleanup was skipped. Put driver.quit() in a finally block so the session closes even when capture raises an exception.

7. Performance, reliability, and cost

The Selenium API references establish the method and output forms, but they do not provide a performance benchmark for your site, browser, or driver. Capture time and payload size depend on the rendered page and environment; measure them in your own workload. Base64 represents binary data as text, so account for its larger transport representation when sending large screenshots. Close sessions reliably, bound navigation and service timeouts, and avoid starting more browser sessions than your host can support.

Selenium itself is the browser automation method described above. If you want a hosted screenshot API without managing browser setup, ScreenshotNeo accepts one GET request with a URL and returns an image or PDF. Its clean-shot flow accepts consent banners like a visitor and removes more than 60 known consent platforms, newsletter popups, and chat widgets; each step can be turned off. Only clean shots are billed: bot checks, CAPTCHAs, blank pages, timeouts, failed loads, and cache hits cost nothing, with the outcome reported in response headers. Its MCP server provides take_screenshot, get_page_info, and capture_pdf for AI agents.

8. Or skip the browser setup

ScreenshotNeo’s API returns an image or PDF from a URL. See the API documentation for options.

curl -G "https://api.screenshotneo.com/v1/shot" -d access_key=YOUR_API_KEY --data-urlencode url=https://stripe.com -o shot.webp
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)
const q = new URLSearchParams({ access_key: 'YOUR_API_KEY', url: 'https://stripe.com' });
const res = await fetch(`https://api.screenshotneo.com/v1/shot?${q}`);
if (!res.ok) throw new Error(`Screenshot request failed: ${res.status}`);
await require('node:fs/promises').writeFile('shot.webp', Buffer.from(await res.arrayBuffer()));
  • Cookie banners, popups, and chat widgets are removed before the shot.
  • Bot checks, blank pages, and failed loads are never billed.
  • An MCP server lets AI agents take screenshots.
  • 1,000 screenshots a month are free with no card; paid plans start at $5 for 3,000.

Sign up free for 1,000 screenshots a month, with no card required.

9. FAQ

Does the Python method return a data URL?

No. It returns the Base64 payload. Add the appropriate prefix yourself if the consumer needs a data URL.

Should I store the screenshot as Base64?

Use Base64 when a text representation is required. For file storage or binary image processing, PNG bytes or a PNG file may fit better.

Can I use the same method name in every Selenium language?

No. Binding APIs differ; Python, Java, and JavaScript use different calls and return types.

Does this capture a whole long page?

The documented Python method captures the current window. Full-page behavior is not guaranteed across implementations.