ScreenshotNeo

BlogComparisons

Selenium Python: save_screenshot() vs. get_screenshot_as_file()

save_screenshot() and get_screenshot_as_file() are aliases in Selenium Python. Learn their return values, paths, limits, errors, and alternatives.

By the ScreenshotNeo team30 September 20267 min read

Selenium Python: save_screenshot() vs. get_screenshot_as_file()

Short answer: In the current Selenium Python binding, save_screenshot(filename) and get_screenshot_as_file(filename) do the same thing. save_screenshot() delegates directly to get_screenshot_as_file(). Both capture the current WebDriver window as a PNG file, return True when the file is written, and return False when an operating-system or file I/O error prevents the write.

Use save_screenshot() for new code because the name is shorter and clearer. Keep get_screenshot_as_file() in an existing project when consistency matters; changing the method name does not change behavior.

At a glance

Question Answer
Are they different APIs? No. save_screenshot() is an alias that calls get_screenshot_as_file().
What do they capture? The current WebDriver window.
What format do they write? PNG bytes.
Where do they write? To the filesystem path you pass.
What do they return? True on success and False after an OSError/I/O failure.
What filename should you use? A full path ending in .png.
Do they make a full-page screenshot? Not automatically. These methods are documented for the current window; do not assume vertical page stitching.

Use save_screenshot() in new Python code

This complete example opens a page, creates an output directory, saves a PNG, checks Selenium’s boolean result, and always closes the browser.

These Selenium methods capture the current WebDriver window; full-page stitching requires a separate browser or driver technique.
These Selenium methods capture the current WebDriver window; full-page stitching requires a separate browser or driver technique.
from pathlib import Path
from selenium import webdriver
from selenium.webdriver.chrome.options import Options

output = Path("screenshots") / "home.png"
output.parent.mkdir(parents=True, exist_ok=True)

options = Options()
# Remove this line if you want to watch the browser.
options.add_argument("--headless=new")

browser = webdriver.Chrome(options=options)
try:
    browser.get("https://example.com")

    written = browser.save_screenshot(str(output))
    if not written:
        raise RuntimeError(f"Selenium could not write {output}")

    print(f"Saved {output}")
finally:
    browser.quit()

Pass a string path, including the .png suffix. Using pathlib.Path is convenient, but convert it with str() for broad Selenium compatibility.

The equivalent get_screenshot_as_file() call

Replace the save line with this:

written = browser.get_screenshot_as_file("screenshots/home.png")

The result, file format, capture target, and failure behavior are the same. The longer name can be useful when reading old code because it explicitly says that the destination is a file.

How the two methods behave

Implementation relationship

The current Python binding implements save_screenshot() as a direct call to get_screenshot_as_file(). There is no second capture path, different encoder, or different return contract to account for.

Filesystem output

get_screenshot_as_file() obtains PNG data, opens the requested target in binary-write mode, writes the bytes, and returns True. If an OSError occurs while opening or writing the target, it returns False.

Filename extension

A filename that does not end in .png produces a UserWarning. Use a PNG suffix even when the operating system would allow another extension; the bytes are still PNG data.

Current window versus full page

Both names refer to the current WebDriver window. They do not, by themselves, promise a full-page image stitched from every vertical section. Full-page behavior depends on a separate browser or driver capability and should not be inferred from either method name.

When you need screenshot data in memory

Neither file-saving method is ideal when the next step uploads, hashes, or processes the image in memory. Use Selenium’s byte or base64 methods instead.

Raw PNG bytes

png_bytes = browser.get_screenshot_as_png()
with open("screenshots/home.png", "wb") as image_file:
    image_file.write(png_bytes)

Base64 text

png_base64 = browser.get_screenshot_as_base64()
print(png_base64[:40])

The byte method is usually the simplest choice for an HTTP upload or an image library. Base64 is useful when the receiving interface explicitly expects text.

Choosing the right method

Requirement Use
Write a PNG to disk save_screenshot(path)
Preserve an existing codebase’s naming get_screenshot_as_file(path)
Upload or inspect bytes without a temporary file get_screenshot_as_png()
Send screenshot data as text get_screenshot_as_base64()
Capture a guaranteed full page Use a documented browser/driver-specific full-page technique; these two methods alone do not guarantee it.

Reliable file-saving checklist

  1. Create the parent directory before calling Selenium.
  2. Pass an absolute or otherwise unambiguous path when running in CI.
  3. End the filename with .png.
  4. Check the returned boolean instead of assuming the file exists.
  5. Keep the browser alive until the call finishes.
  6. Call quit() in a finally block.
  7. Verify the resulting file separately when your pipeline needs a non-empty artifact.

Troubleshooting

The method returns False

Cause: Selenium encountered an operating-system or file I/O error while opening or writing the target.

Fix: Check that the parent directory exists, the process has write permission, the path is valid for the operating system, and the destination is not read-only. Log the exact path and retry only after fixing the filesystem condition.

The file is saved somewhere unexpected

Cause: A relative path is resolved from the process’s current working directory, which may differ in an IDE, test runner, container, or CI job.

Fix: Resolve the path before passing it:

output = Path("screenshots/home.png").resolve()
output.parent.mkdir(parents=True, exist_ok=True)
if not browser.save_screenshot(str(output)):
    raise IOError(f"Could not write {output}")

A warning appears about the filename

Cause: The filename does not end in .png.

Fix: Rename it with the PNG suffix. Do not use .jpg or .webp with these methods; they write PNG output.

The screenshot is only the visible viewport

Cause: These methods target the current WebDriver window and do not promise automatic page stitching.

Fix: Decide whether you need viewport capture or a full-page result, then use a browser/driver-specific full-page feature when required. Do not treat the two method names as evidence of full-page support.

The screenshot is blank or shows the wrong page

Cause: Capture happens at the moment the call runs. Navigation, redirects, delayed rendering, or an unselected tab can leave the current window in an unexpected state.

Fix: Confirm the current URL and wait for the page state your workflow requires before calling the screenshot method. The file-writing methods themselves do not add a page readiness wait.

The browser closes before the image is written

Cause: The driver was quit or lost before the screenshot command completed.

Fix: Keep the call inside the driver lifetime and place cleanup after it, as shown in the complete example.

Performance, reliability, and cost considerations

Performance

The two file methods have the same capture and write work because one delegates to the other. Renaming the method will not make screenshots faster. If disk I/O is the bottleneck, capture PNG bytes with get_screenshot_as_png() and pass them directly to the next in-memory step.

ScreenshotNeo removes common consent banners, popups, and chat widgets before returning the image.
ScreenshotNeo removes common consent banners, popups, and chat widgets before returning the image.

Reliability

Treat the boolean return value as part of the API contract. A successful WebDriver command does not replace checking whether the operating system accepted the file write. Use deterministic paths, create directories explicitly, and preserve failed-run logs with the path you attempted.

Cost

These Selenium methods run in your own browser automation process, so their operational cost comes from the browser, driver, compute, storage, and any infrastructure around that process. The method choice itself does not add a separate Selenium screenshot fee.

Or skip the browser setup

If you need a website image rather than a browser automation workflow, ScreenshotNeo provides a single GET request that returns a PNG, JPEG, WebP, or PDF. Its capture process accepts cookie and consent banners like a visitor, then removes more than 60 known consent platforms, newsletter popups, and chat widgets before the shot. Each cleanup step can be turned off.

Only clean shots are billed. Bot checks and CAPTCHAs, blank pages, timeouts, failed loads, and cache hits cost nothing, and the response identifies the result with X-Page-Verdict and X-Billed headers. ScreenshotNeo also provides an MCP server with take_screenshot, get_page_info, and capture_pdf tools for Claude, Cursor, and other MCP clients.

See the ScreenshotNeo API documentation for all options. This is the one-call version of the same basic job:

cURL

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

Python

import requests

r = requests.get(
    "https://api.screenshotneo.com/v1/shot",
    params={"access_key": "YOUR_API_KEY", "url": "https://stripe.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://stripe.com'
});
const res = await fetch(`https://api.screenshotneo.com/v1/shot?${q}`);
if (!res.ok) throw new Error(`Screenshot failed: ${res.status}`);
const image = Buffer.from(await res.arrayBuffer());
require('node:fs').writeFileSync('shot.webp', image);

ScreenshotNeo includes full-page capture with lazy images loaded, CSS-selector element capture, dark mode, device presets and custom viewports, retina scale, PDF controls, custom CSS and JavaScript, clicks, waits, request blocking, headers, cookies, user agents, authorization, timezone, geolocation, transparent backgrounds, resizing, configurable caching, signed links, asynchronous jobs with signed webhooks, bulk capture for up to 100 URLs per call, a usage API, and an OpenAPI specification. Its parameter names are compatible with those used by other screenshot APIs, which can simplify migration.

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

FAQ

Which spelling should a new project use?

Use save_screenshot(). It is the concise name and has the same behavior as the longer method.

Can I save JPEG or WebP with these methods?

No. These Selenium methods write PNG data. Use a separate conversion step if another image format is required.

Why does Selenium return a boolean instead of raising every file error?

The file-saving method reports an OSError/I/O failure by returning False; successful writes return True. Your code should check that value.

Does changing the method name affect the screenshot?

No. Both methods capture the same current WebDriver window and use the same file-writing implementation.

How can I avoid managing a screenshot path?

Call get_screenshot_as_png() for bytes or get_screenshot_as_base64() for a base64 string.