ScreenshotNeo

BlogHow-to

Selenium screenshot file save karne ka tareeka in Python

Save a Selenium screenshot to a PNG file in Python, choose the right capture method, and fix common file and browser errors.

By the ScreenshotNeo team4 October 20262 min read

Use Selenium Python’s driver.save_screenshot("screenshot.png") to save a PNG of the browser’s current window. Create the destination folder first, use a filename ending in .png, and check the method’s return value if a failed save matters. The path is resolved from the Python process’s working directory unless you provide a full path.

1. Save the current browser window to a PNG

This complete example opens a page, creates an output directory if needed, saves the screenshot, checks for an I/O failure, and closes the browser. Install Selenium with python -m pip install selenium and ensure a compatible browser and driver setup is available.

from pathlib import Path
from selenium import webdriver

output_dir = Path("screenshots")
output_dir.mkdir(parents=True, exist_ok=True)
screenshot_path = output_dir / "page.png"

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

print(f"Saved screenshot to {screenshot_path.resolve()}")

Selenium documents save_screenshot(filename) as saving a PNG image of the current window. It returns True when successful and False on an I/O error; use the .png extension. See the Selenium Python WebDriver API.

Use an absolute path when the output location is unclear

A relative filename such as screenshots/page.png is relative to the process’s current working directory, which may differ depending on how you start the script, IDE, test runner, or scheduled job. To choose a fixed location, pass an absolute path:

from pathlib import Path

screenshot_path = Path("/tmp/selenium-shots/page.png")
screenshot_path.parent.mkdir(parents=True, exist_ok=True)
saved = driver.save_screenshot(str(screenshot_path))
if not saved:
    raise OSError(f"Could not save screenshot to {screenshot_path}")

Change the example path to a directory that exists and that the Python process can write to. Selenium recommends a full path when saving screenshots.

2. Choose file, bytes, or Base64 output

Method Result Use it when
driver.save_screenshot(path) Writes a PNG file and returns a success result You want a screenshot on disk
driver.get_screenshot_as_png() PNG bytes Your Python code will process or store the image itself
driver.get_screenshot_as_base64() Base64-encoded image data You need encoded image data, for example to embed it in HTML

The bytes and Base64 methods let you choose how to handle the screenshot without first asking Selenium to write the file. The Selenium API documents both methods and notes Base64 can be useful for embedding in HTML. See the WebDriver API reference.

from pathlib import Path

# Save Selenium's PNG bytes with Python file I/O.
png_bytes = driver.get_screenshot_as_png()
Path("screenshots/from-bytes.png").write_bytes(png_bytes)

# Get Base64 data when an encoded representation is needed.
image_base64 = driver.get_screenshot_as_base64()

The folder must exist before writing bytes too. Use save_screenshot for the direct-to-file case; use bytes or Base64 when another part of your program needs that representation.

3. Capture an element or a full page

Capture one element

If you need one element rather than the current window, locate it and use the element screenshot API exposed by your installed Selenium version:

from selenium.webdriver.common.by import By

element = driver.find_element(By.CSS_SELECTOR, "main")
saved = element.screenshot("screenshots/main.png")
if not saved:
    raise OSError("Could not save element screenshot")

This captures the selected element. The selector must match an element on the loaded page. Element dimensions, visibility, and browser behavior can affect whether it can be captured as expected.

Capture a full document

driver.save_screenshot() is documented as capturing the current window. Do not assume it always captures the whole scrollable document. Selenium’s Firefox API documents save_full_page_screenshot(filename) for a full-document PNG; check the API for your installed browser and driver before relying on that method. It is Firefox-specific in the cited documentation, not a universal WebDriver guarantee. See the Selenium Firefox WebDriver API.

4. Make the capture more reliable

  1. Navigate to the target URL with driver.get().
  2. Wait for the page state or element you need before capturing; a navigation call alone does not guarantee that every dynamic element or image has finished rendering.
  3. Confirm the target window or tab is selected and the desired page is displayed.
  4. Create the destination directory and choose a writable path ending in .png.
  5. Save and check the result. Keep the driver open until the capture completes.
  6. Close the driver with a context manager or call driver.quit() after capture.

For pages that update asynchronously, use an explicit wait for the content that matters instead of relying on a fixed delay:

from pathlib import Path
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.support.ui import WebDriverWait

out = Path("screenshots/page.png")
out.parent.mkdir(parents=True, exist_ok=True)

with webdriver.Chrome() as driver:
    driver.get("https://example.com")
    WebDriverWait(driver, 15).until(
        EC.visibility_of_element_located((By.CSS_SELECTOR, "main"))
    )
    if not driver.save_screenshot(str(out)):
        raise OSError(f"Could not save {out}")

Replace main with a selector that indicates the content you need is ready. A wait can help with page readiness; it does not guarantee every remote image or animation has settled.

5. Troubleshoot screenshots that are missing or wrong

Symptom Likely cause Fix
No file appears The relative path points to a different working directory than expected. Print Path.cwd() or use and log an absolute path.
Save fails or returns False The directory does not exist, the path is invalid, or the process cannot write there. Create the parent directory, check permissions and free space, and inspect the return value.
The image is not a PNG The filename has a misleading or unsupported extension. Use a .png filename for Selenium’s screenshot method.
The screenshot shows an older or incomplete page The capture happened before the target content rendered, or the wrong tab/window was active. Wait for a page-specific element and verify the selected window before capture.
The browser closes before the file is written The driver was quit before the screenshot call completed. Save first, then exit the context manager or call quit().
The screenshot is only the visible viewport The standard method captures the current window rather than promising a full-document image. Use a browser-specific full-page API supported by your installed driver, or capture and stitch scroll segments if appropriate.
Element screenshot raises an error The selector did not match, or the element is not in a capturable state. Wait for the element, confirm the selector, and check its visibility and dimensions.

The directory, permissions, working-directory, and rendering checks are practical file and browser troubleshooting steps. Selenium’s documented guarantees are the PNG output, current-window scope, and the Boolean result for I/O success.

6. Performance, reliability, and cost

Saving a screenshot is a browser capture plus a local file write. The cited Selenium API establishes no universal speed or image-size figure; actual time and output size depend on the page and environment. Reuse a browser session when capturing multiple pages if your workflow allows it, and close it when finished. Avoid treating an arbitrary sleep as proof that a dynamic page is ready; wait for the content you need.

For automated jobs, use an explicit output directory, unique filenames where captures must not overwrite each other, and check the return value or catch file errors. Selenium runs in your environment, so the screenshot itself does not incur a ScreenshotNeo charge. Browser and compute costs depend on where you run the automation.

7. Or skip the browser setup

ScreenshotNeo is a website screenshot API and MCP server. One GET request returns an image or PDF, without requiring you to install and manage a browser for this capture. See the API documentation.

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)

ScreenshotNeo removes supported cookie and consent banners, newsletter popups, and chat widgets before capture. Bot checks, blank pages, failed loads, timeouts, and cache hits are not billed; response headers report the page verdict and billing status. Its MCP server offers screenshot tools for AI agents. 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. FAQ

What file extension should I use?

Use .png with Selenium’s save_screenshot method.

Does Selenium create the screenshot folder?

Do not rely on it to create directories. Create the parent folder in Python before saving.

Can I save the screenshot without writing it immediately?

Yes. Use get_screenshot_as_png() for PNG bytes or get_screenshot_as_base64() for encoded data.

Does save_screenshot capture the full page?

It is documented for the current window. Full-document support depends on the browser-specific API; Selenium documents a Firefox full-page method separately.