ScreenshotNeo

BlogHow-to

Capture Screenshots of Authenticated Web Pages with Selenium Cookies

Set up an authorized Selenium session, add cookies in the right domain context, and save a validated screenshot of an authenticated page.

By the ScreenshotNeo team4 October 20268 min read

To capture an authenticated page with Selenium, establish an authorized session, navigate to the cookie’s valid domain before adding it, open the target page, and call driver.save_screenshot("page.png"). Check the method’s return value: True means the PNG was saved, while False indicates an I/O error. A successful file write does not prove the page is authenticated, so validate the rendered page separately.

This guide uses Python and Selenium WebDriver. It covers repeatable test setup, cookie scope, current-window versus full-document capture, output validation, common failures, and a one-call hosted alternative.

1. Install Selenium and prepare an authorized test session

Install Selenium in your Python environment:

python -m pip install selenium

Selenium’s browser automation guidance recommends preparing application state outside a repeated browser login flow when possible. For tests, an application-supported API login or other approved setup can establish a test account’s state and provide a session cookie. The exact mechanism depends on the application and its authentication design. Selenium’s guidance explains that avoiding browser login before every test can improve test speed and stability: Generating application state.

Use a test account and a session issued for that environment. Do not paste a production session cookie into source code, logs, screenshots, or a shared CI configuration. Cookies carry session state; treat them as credentials. The code below uses a placeholder and is a workflow example, not a tested execution.

WebDriver can add, retrieve, and delete cookies in the current browsing context. Before calling add_cookie, navigate to a page on a domain for which the cookie is valid. Otherwise, the browser may reject it or it may not apply to the target page. See Selenium’s cookie documentation.

A cookie’s applicability can depend on its domain and path, and on attributes such as expiry, secure, httpOnly, and sameSite. Use the cookie definition and value issued by the application’s supported test setup; do not guess attributes or copy a cookie from an unrelated domain. For the Python WebDriver cookie API, see the Selenium Python WebDriver reference.

3. Capture the authenticated page in Python

This example assumes you have an authorized test session value. It navigates to the application domain, injects the cookie, opens a report page, and saves the current browser window as a PNG. Replace the domain, paths, cookie name, and placeholder with values for your test application.

from pathlib import Path
from selenium import webdriver

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

driver = webdriver.Chrome()
try:
    # First visit a page on the cookie's valid domain.
    driver.get("https://example.test/account")

    # Supply only an authorized session value from your test setup.
    driver.add_cookie({
        "name": "session",
        "value": "<authorized test session value>",
    })

    # Load the authenticated destination after setting the cookie.
    driver.get("https://example.test/account/report")

    # save_screenshot captures the current window as PNG.
    saved = driver.save_screenshot(str(output))
    if not saved:
        raise OSError(f"Could not save screenshot to {output}")
finally:
    driver.quit()

The save_screenshot method documents a boolean result: it returns False on an I/O error and otherwise True. Give it an explicit path and create its parent directory first. See the Python WebDriver API reference.

After navigation, verify that the expected authenticated content is present before treating the image as useful. A login redirect, expired session, or access-denied page can still be written successfully to a PNG file.

4. Establish state through an application API when appropriate

Repeatedly navigating through a login form makes tests depend on the login UI and its extra steps. Selenium’s test-practices guidance recommends generating application state through another method, with API authentication followed by setting a cookie as an example. The right approach depends on the test environment and the application’s supported authentication flow.

  1. Use an approved test endpoint or setup mechanism to authenticate a test account.
  2. Obtain the session state in the form the application expects.
  3. Navigate WebDriver to a page on the session cookie’s valid domain.
  4. Add the cookie, then navigate to the authenticated target.
  5. Check for a page-specific authenticated marker before capturing.

This pattern does not bypass access controls. It is for authorized testing with credentials and session state provided by the application or test environment. Some sites use identity-provider redirects, multiple cookies, device checks, or other state, so a single copied cookie may not be sufficient.

5. Understand the screenshot scope

The Python WebDriver save_screenshot call captures the current window and writes PNG. It should not be described as a universal full-document capture method. If the image must include content beyond the current viewport, confirm support for your specific browser and Selenium binding.

The reviewed Firefox Python API documents full-document screenshot methods separately. That is browser-specific documentation; do not assume the same method is available across every browser and binding. Consult the Firefox WebDriver API reference and the API reference for your installed browser driver before relying on full-page behavior.

Need Approach Check
Visible browser window Python driver.save_screenshot(path) Check the boolean result and inspect page state.
Entire document Use a documented full-document method supported by the specific browser and binding. Verify current API support for your installed Selenium and browser versions.

6. Validate the result and protect session data

  • Validate authentication separately: check for an expected account element, URL, or other application-specific marker before saving.
  • Validate the file write: check the return value and use a deterministic path.
  • Keep outputs private: authenticated screenshots can contain account or personal data. Restrict access and retention according to your application’s handling requirements.
  • Keep cookies out of logs: avoid printing cookie values or placing them in exception messages.
  • Always close the session: put driver.quit() in a finally block so it runs if navigation or capture raises an error.

7. Troubleshooting

Symptom Likely cause Fix
add_cookie fails or the cookie has no effect The browser is not on a domain that matches the cookie, or the cookie’s scope or attributes do not match the application. Navigate to the correct site domain first. Use the application-issued cookie definition and check domain, path, expiry, secure, and same-site requirements.
Screenshot shows a login page The session was not established, expired, or is incomplete for this application. Confirm the approved test login/setup succeeded, check the cookie’s validity and scope, then verify the post-login URL and an authenticated page marker.
The file is missing or the call returns False The output directory may not exist or the process may lack permission to write there. Create the parent directory, use an explicit path, and ensure the running process can write to it. Check the documented boolean result.
The image is cropped to the viewport save_screenshot captures the current window, not a cross-browser full-document image. Check whether your browser and Python binding document a full-document method, and use that supported API if appropriate.
Capture appears blank or incomplete The target may not have finished rendering, may have redirected, or may be displaying an error state. Inspect the current URL and page state before capture. Wait using a condition appropriate to the application and verify the expected content.
Browser remains running after a failure Cleanup did not execute after an exception. Wrap browser work in try/finally and call driver.quit() from the finally block.

8. Performance, reliability, and cost considerations

For repeated tests, setting application state through an approved API or setup hook can avoid repeating browser login steps; Selenium explicitly connects that practice with improved test speed and stability. The actual time saved depends on the application and test environment, and no general benchmark follows from the documentation.

Reliability depends on keeping setup aligned with the application’s session rules. Reuse only session state intended for the test, verify authentication after navigation, and pin your assumptions to the browser and Selenium binding you run. A screenshot API returning success means the image was written; it does not establish that the captured page is the expected page.

For a self-hosted Selenium workflow, plan for the browser process and output storage your environment uses; the supplied Selenium references do not provide a cost benchmark for this capture pattern. For managed screenshot volume, ScreenshotNeo offers 1,000 screenshots per month on its free plan with no card, then paid plans starting at $5 for 3,000 shots. Its billing rule is that bot checks, blank pages, timeouts, failed loads, and cache hits are not billed; each response identifies the page verdict and billing status in headers.

9. Or skip the browser setup

ScreenshotNeo is a website screenshot API and MCP server for developers. One GET request takes a URL and returns a PNG, JPEG, WebP, or PDF. Its cookie, popup, and chat cleanup can remove known consent platforms, newsletter popups, and chat widgets before capture; each cleanup step can be turned off. It does not require you to maintain a Selenium browser session for this URL-based capture.

Use your ScreenshotNeo API key as YOUR_API_KEY. See the ScreenshotNeo API documentation for request options.

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,
)
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}`);
  • Cookie banners, popups, and chat widgets are removed before the shot.
  • Bot checks, blank pages, timeouts, and failed loads are never billed; cache hits are also not billed.
  • An MCP server lets AI agents, including Claude and Cursor, take screenshots with tools such as take_screenshot, get_page_info, and capture_pdf.
  • 1,000 screenshots a month are free with no card; paid plans start at $5 for 3,000. Every feature is on every plan.

Sign up free for ScreenshotNeo and get 1,000 screenshots a month with no card.

10. Frequently asked questions

Does a screenshot prove that login succeeded?

No. It proves only that an image was written when the save call succeeds. Check the page URL and authenticated content independently.

Only use session values you are authorized to use and that the application supports for the test context. A cookie copied from another context is not guaranteed to authenticate the site.

Can I save the screenshot as JPEG with save_screenshot?

The documented Python method saves PNG. For other output formats or a different capture workflow, consult the relevant browser API or use a service that supports the requested format.

Will the same code work with every Selenium browser?

The basic current-window screenshot call is documented by Python WebDriver, but full-document capture support varies by browser and binding. Verify the specific API you intend to use.

Further reading

ScreenshotNeo is a website screenshot API and MCP server by ScreenshotNeo. Use Selenium when the test needs a controlled authenticated browser session; use the API when a URL-based screenshot is the right fit.