October DealsAmazon USOctober deal check: compare before you payAmazon US: current deals, useful picks and tech finds.Check DealsClean PCRecommendedOne scan can reveal what keeps slowing WindowsLook for cleanup and repair opportunities.Run ScanOctober DealsAmazon USDeal season is back - check today's better picksAmazon US: current deals, useful picks and tech finds.See Picks×
Skip to content
World desk5 min

How to Take Screenshots in Selenium: Examples and Code

Capture the current Selenium browser view or one element, save PNGs in Python, JavaScript, or Java, and understand output formats and full-page limitations.
Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Use Selenium’s screenshot method for the current browser view, or a WebElement screenshot method for a single element. In Python, call driver.save_screenshot("screenshot.png"); in JavaScript, await driver.takeScreenshot() and write the returned Base64 PNG to a file. The exact method and capture extent depend on the language binding and browser driver.

Take and save a screenshot in Python

Selenium’s official browser-interactions guide shows save_screenshot saving a PNG file. The method returns a Boolean: True when saving succeeds and False on an I/O error. Make sure the destination directory exists and is writable.

from pathlib import Path
from selenium import webdriver

output = Path("artifacts") / "screenshot.png"
output.parent.mkdir(parents=True, exist_ok=True)

driver = webdriver.Chrome()
try:
    driver.get("https://example.com")
    saved = driver.save_screenshot(str(output))
    if not saved:
        raise OSError(f"Could not save screenshot to {output}")
finally:
    driver.quit()

This captures the current browsing context after navigation. If the screenshot must show a particular state, arrange that state before calling the method; a screenshot call does not itself establish that the page has finished whatever work your test expects.

Get image data without saving a file

Use get_screenshot_as_png() when you need PNG bytes for in-memory processing, or get_screenshot_as_base64() when you need a string for embedding or transport.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
png_bytes = driver.get_screenshot_as_png()
base64_png = driver.get_screenshot_as_base64()

These return bytes and str, respectively. The driver must still be active when you request the screenshot. See the Python WebDriver API.

Capture one element instead of the whole view

If you need a heading, control, or chart rather than the current window, use an element screenshot method when it is available in your binding. Selenium’s JavaScript WebElement API defines the capture as the visible region inside the element’s bounding rectangle; it is not necessarily a capture of content clipped outside that visible region.

const heading = await driver.findElement(By.css('h1'));
const encodedPng = await heading.takeScreenshot();
require('node:fs').writeFileSync('heading.png', encodedPng, 'base64');

This JavaScript example follows Selenium’s documented element usage. The element must be located in the current page context before capture. See the JavaScript WebElement API.

JavaScript: save the current screenshot

The JavaScript WebDriver method takeScreenshot() resolves to Base64-encoded PNG data. Write it using Node’s Base64 encoding option to produce a PNG file.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
const encodedPng = await driver.takeScreenshot();
require('node:fs').writeFileSync('screenshot.png', encodedPng, 'base64');

The documented capture extent is best-effort: the API prefers the entire page, then the current window, then the visible portion of the current frame, then the entire display containing the browser. Do not assume a generic WebDriver screenshot call produces a full-page image in every browser-driver combination. See the JavaScript WebDriver API.

Java: capture and copy the screenshot file

Selenium’s official usage example casts the driver to TakesScreenshot, requests a file, and copies it to the desired destination. The file-copy call depends on the dependencies in your Java project; this outline shows the Selenium capture pattern.

File source = ((TakesScreenshot) driver).getScreenshotAs(OutputType.FILE);
Files.copy(source.toPath(), Path.of("image.png"), StandardCopyOption.REPLACE_EXISTING);

Import java.io.File, java.nio.file.Files, java.nio.file.Path, java.nio.file.StandardCopyOption, and Selenium’s OutputType and TakesScreenshot types. Keep the driver session open until the copy finishes. Selenium’s official browser interactions guide includes the Java screenshot usage pattern.

Choose the right screenshot output

Need Use What to know
Test artifact on disk Save a PNG file Use a writable path; Python reports I/O failure with a False result.
Image processing in Python get_screenshot_as_png() Returns PNG bytes without requiring an intermediate file.
Embedding or transport Base64 output Python offers get_screenshot_as_base64(); JavaScript takeScreenshot() resolves to Base64 PNG.
One heading or control WebElement screenshot JavaScript documents the visible region within the element’s bounding rectangle.
Entire page Driver screenshot, subject to implementation JavaScript documents page capture as a best-effort preference, not a universal guarantee.

Or skip the browser setup

If you need a website image without starting and managing a Selenium browser session, ScreenshotNeo returns a screenshot or PDF from one request. It can accept cookie and consent banners and remove 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 are not billed, and response headers report the page verdict and billing status. Its MCP server includes take_screenshot, get_page_info, and capture_pdf for AI agents.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
curl -G "https://api.screenshotneo.com/v1/shot" -d access_key=YOUR_API_KEY --data-urlencode url=https://example.com -o shot.webp

See the ScreenshotNeo API documentation for the request options. The Free plan includes 1,000 screenshots per month with no card; paid plans start at $5 for 3,000. Sign up for 1,000 free screenshots a month, with no card.

Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.Support on Ko-Fi

Troubleshooting Selenium screenshots

The file is missing or Python returns False

  • Confirm the parent directory exists and the process can write to it.
  • Use an explicit path and check the Boolean result from save_screenshot.
  • For other bindings, verify the destination path and the file-copy step separately.

The image is blank or shows the wrong state

  • Capture only after your script has reached the state you intend to document.
  • Check that the expected window and frame are active: screenshot methods capture the current browsing context.
  • For one element, locate the intended element in the current page before calling its screenshot method.

The image is not full-page

Do not treat full-page capture as a cross-browser guarantee. The JavaScript API describes capture extent as best-effort; behavior can depend on the browser and driver. If a complete page image is essential, confirm the behavior for the specific binding and browser-driver setup you use.

Reliability and session handling

Selenium WebDriver controls a browser locally or through Selenium Server. Save or consume the image before closing the session, and use a cleanup path such as Python’s try/finally so the browser is quit even when screenshot handling raises an error. Selenium identifies WebDriver as a W3C Recommendation; language bindings have different method names and output mechanics.

Frequently Asked Questions

Does Selenium save screenshots as PNG?

Yes. The documented Python save and screenshot-data methods use PNG, and JavaScript WebDriver returns Base64-encoded PNG data.

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

Can Selenium take a screenshot of a specific element?

Yes. Element screenshot methods exist; JavaScript’s WebElement API describes the captured area as the visible region within the element’s bounding rectangle.

Does Selenium always capture the full page?

No. The JavaScript API describes capture extent as best-effort, so full-page behavior should not be assumed across drivers.

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.

Leave a Reply

Your email address will not be published. Required fields are marked *

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.

More from the Wire

  1. Shenzhen desk3 min
    HONOR Expands Beyond Smartphones With Humanoid Robot RevealHONOR said it unveiled its first humanoid robot at MWC 2026 and named shopping assistance, workplace inspections, and supportive companionship as intended uses. Later Robotics D1 claims and a reported…
  2. Cupertino desk5 min
    Apple Unveils AirPods Max 2: The Upgrade That Should Have Happened Years AgoAirPods Max 2 adds H2-powered audio features and Apple claims up to 1.5× more effective ANC, but its design, Smart Case, and 20-hour battery rating are unchanged. Wired lossless audio…
  3. Cupertino desk4 min
    Apple’s OLED Touch MacBooks Are Coming—but the Dynamic Island Is the Real GambleApple has not announced an OLED touchscreen MacBook, but reports point to high-end models arriving in late 2026 or early 2027. The reported Mac Dynamic Island could be useful, but…
Recommended PC Tool
Recommended PC Tool
Crashes, No Sound, or Screen Glitches?Free driver scan
PC Slower Than It Used to Be?Free scan - under a minute

Two free Windows tools

One Free Minute Could Fix That PC

Before you go - each of these free tools takes about a minute and tackles what quietly slows a Windows PC down.

Special offer. View Outbyte info, uninstall instructions, EULA, and Privacy Policy.