ScreenshotNeo

BlogHow-to

How to Take Screenshots in Selenium: Examples and Code

Capture and save Selenium screenshots in Python and JavaScript, including element images, PNG bytes, and Base64 output, with practical fixes for common issues.

By the ScreenshotNeo team4 October 20267 min read

To take a screenshot in Selenium, navigate to the page and call the screenshot method on the active WebDriver. In Python, use driver.save_screenshot("screenshot.png"). In JavaScript, await driver.takeScreenshot() and write the returned Base64 PNG to a file. For a single control or heading, capture the WebElement when your language binding supports it.

This guide shows how to save a browser screenshot, get image data in memory, capture an element, and handle timing, paths, and capture-scope issues. Selenium drives a browser locally or through Selenium Server; its WebDriver is a W3C Recommendation. See the [official Selenium browser interactions guide](https://www.selenium.dev/documentation/webdriver/interactions/windows/) for the language-specific usage examples and APIs. Selenium WebDriver documentation.

1. Capture a screenshot in Python

Install Selenium in your Python environment, make sure the browser and driver setup is available for your Selenium installation, then run this script. It opens a page, saves a PNG, checks whether saving succeeded, and closes the browser even if capture fails.

from selenium import webdriver

 driver = webdriver.Chrome()
 try:
     driver.get("https://example.com")
     saved = driver.save_screenshot("screenshot.png")
     if not saved:
         raise OSError("Screenshot could not be saved")
 finally:
     driver.quit()

Remove the leading spaces before driver, try, finally, and the indented statements if copying this snippet exactly; the complete correctly indented version is:

from selenium import webdriver

driver = webdriver.Chrome()
try:
    driver.get("https://example.com")
    saved = driver.save_screenshot("screenshot.png")
    if not saved:
        raise OSError("Screenshot could not be saved")
finally:
    driver.quit()

save_screenshot(filename) writes the current window to a PNG file and returns True on success or False on an I/O error. Ensure the parent folder exists and the process can write to it. The API also provides get_screenshot_as_file(filename), which has the same file-oriented purpose and boolean result. Python WebDriver API.

2. Capture a screenshot in JavaScript

The JavaScript WebDriver method returns a promise resolving to Base64-encoded PNG data. Write it with the Base64 encoding option so the file contains PNG bytes rather than the encoded text.

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

(async () => {
  const driver = await new Builder().forBrowser('chrome').build();
  try {
    await driver.get('https://example.com');
    const encodedPng = await driver.takeScreenshot();
    fs.writeFileSync('screenshot.png', encodedPng, 'base64');
  } finally {
    await driver.quit();
  }
})();

This uses the Selenium JavaScript package and Node’s built-in filesystem module. The screenshot describes the current page/browsing context; the documented capture extent is best effort, so do not assume every browser and driver will return a full-page image. JavaScript WebDriver API.

3. Capture one element

Element capture is useful for a chart, heading, result panel, or control when the rest of the page is irrelevant. Find the element after navigation and save the returned Base64 PNG:

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

(async () => {
  const driver = await new Builder().forBrowser('chrome').build();
  try {
    await driver.get('https://example.com');
    const heading = await driver.findElement(By.css('h1'));
    const encodedPng = await heading.takeScreenshot();
    fs.writeFileSync('heading.png', encodedPng, 'base64');
  } finally {
    await driver.quit();
  }
})();

An element screenshot covers the visible region inside that element’s bounding rectangle. It is not a promise to capture content outside the visible element region. For an element that is missing, first confirm the selector and that the intended page state has loaded. JavaScript WebElement API.

4. Choose the screenshot output form

Need Use Notes
Test artifact on disk Save PNG to a file Use a writable path and retain the file as your test runner’s artifact.
In-memory image processing in Python get_screenshot_as_png() Returns PNG bytes.
Embed or transport screenshot data Base64 Python exposes get_screenshot_as_base64(); JavaScript takeScreenshot() resolves to Base64 PNG.
One component only Element screenshot JavaScript WebElement API documents the visible bounding rectangle region.
png_bytes = driver.get_screenshot_as_png()
base64_png = driver.get_screenshot_as_base64()

In Python, the first value is bytes and the second is str. Use bytes for image libraries or direct binary writes; use Base64 when the receiving interface expects encoded image data. Python screenshot API details.

5. Full-page screenshots and capture scope

A generic screenshot call captures the active browsing context, but full-page behavior is not universal. The JavaScript API describes a best-effort preference: entire page, current window, visible portion of the current frame, then the display containing the browser. The actual extent can depend on the browser and driver. If the image must include the whole document, verify the output in your target environment or use a capture method whose full-page behavior is explicitly supported for your setup. Selenium JavaScript screenshot documentation.

Element screenshots have a narrower, useful scope: the visible portion enclosed by the element’s bounding rectangle. For a full-page artifact, page screenshot behavior and element capture are distinct concerns; cropping a window image is not equivalent to asking the browser to capture an element.

6. Capture the intended page state

  1. Navigate to the target URL.
  2. Wait until the page is in the state your test intends to document.
  3. Confirm the correct browser window and frame are active.
  4. Capture and save or consume the image.
  5. Close the WebDriver session in a finally block or equivalent cleanup path.

Screenshot methods act on the current browsing context. If a screenshot is blank, stale, or unexpectedly scoped, inspect the active window/frame and whether navigation or the UI update had finished before capture. The Selenium API references describe what the screenshot methods return; they do not promise that an application has finished rendering its asynchronous content.

7. cURL, Python, and Node.js with ScreenshotNeo

If the job is to capture a public webpage without launching and managing a Selenium browser, ScreenshotNeo provides a screenshot API and MCP server. The API takes a URL and returns PNG, JPEG, WebP, or PDF. See the ScreenshotNeo API documentation for its options and request details.

cURL

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

Python

import requests

r = requests.get(
    "https://api.screenshotneo.com/v1/shot",
    params={"access_key": "YOUR_API_KEY", "url": "https://example.com"},
    timeout=90,
)
r.raise_for_status()
open("shot.webp", "wb").write(r.content)

Node.js

const q = new URLSearchParams({ access_key: 'YOUR_API_KEY', url: 'https://example.com' });
const res = await fetch(`https://api.screenshotneo.com/v1/shot?${q}`);
if (!res.ok) throw new Error(`Screenshot request failed: ${res.status}`);
const bytes = new Uint8Array(await res.arrayBuffer());
await import('node:fs/promises').then(fs => fs.writeFile('shot.webp', bytes));

ScreenshotNeo accepts cookie or consent banners as a visitor and removes more than 60 known consent platforms, newsletter popups, and chat widgets before capture; each step can be turned off. Bot checks, blank pages, timeouts, failed loads, and cache hits cost nothing, and responses identify the page verdict and billing status in headers. Its MCP server gives AI agents tools named take_screenshot, get_page_info, and capture_pdf.

The free plan includes 1,000 screenshots per month with no card; paid plans start at $5 for 3,000 shots. Sign up for 1,000 free screenshots a month, with no card required.

8. Common problems and fixes

Symptom Likely cause What to do
Python save returns False or raises an I/O error Destination directory does not exist or is not writable. Create the parent directory first, choose a writable path, and check the boolean result.
JavaScript output file is unreadable Base64 text was written as ordinary text instead of decoded. Pass 'base64' as the write encoding as shown above.
Element lookup fails Selector does not match in the current page/frame, or the element is not present yet. Check the selector and browsing context; wait until the target state exists before locating it.
Screenshot is blank or shows an earlier state Capture happened before the intended content appeared, or the wrong window/frame was active. Wait for the relevant state and verify the active browsing context before capture.
Image is only the viewport, not the entire page Full-page capture is implementation-dependent for generic screenshot calls. Check the target browser/driver behavior; do not infer full-page support from a successful screenshot call.
Browser remains running after an exception Session cleanup was skipped. Put capture logic inside try/finally and call driver.quit() in the cleanup block.

9. Performance, reliability, and cost

A screenshot requires a live WebDriver session and browser, whether the browser is local or managed through Selenium Server. Keep the session open only as long as needed, reuse a session when your automation workflow calls for multiple actions, and always close it after the work. The Selenium references do not publish a universal screenshot speed or reliability figure, so capture time depends on the browser, page, and environment.

For dependable artifacts, make capture occur after the state under test is ready, write to a predictable writable location, check file-save outcomes, and preserve the original browser error if image saving also fails. Selenium itself is the browser automation path; infrastructure costs depend on how you run the browser and are not specified by the cited API documentation.

For ScreenshotNeo, the stated billing rule is that only clean shots are billed; bot checks/CAPTCHAs, blank pages, timeouts, failed loads, and cache hits are not. Its plans are Free: 1,000/month; Starter: $5 for 3,000; Growth: $15 for 15,000; Pro: $39 for 60,000; Scale: $99 for 250,000; Business: $249 for 1,000,000. Yearly billing gives two months free, and every feature is on every plan. These prices and included amounts are ScreenshotNeo product facts; consult its site for current plan details.

10. FAQ

How do I take a screenshot in Selenium?

Call the screenshot method on the active driver after navigating to the page. In Python, use save_screenshot; in JavaScript, await takeScreenshot().

Can Selenium save a screenshot as JPEG?

The Selenium methods covered here produce PNG screenshots. Convert the resulting image with an image-processing tool if another format is required.

Can I take a screenshot of an element in Selenium?

Yes. The JavaScript WebElement API exposes takeScreenshot(), which captures the visible region within the element’s bounding rectangle.

Does Selenium always capture the full page?

No universal guarantee follows from the generic WebDriver screenshot call. The documented JavaScript behavior is best effort and can vary by implementation.

Should I save to a file or keep the image in memory?

Save to a file for a durable test artifact; use PNG bytes for in-memory processing; use Base64 when an embedding or transport interface expects encoded data.