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

Use Selenium to authenticate, wait for a reliable marker that appears only after the protected page is ready, and then save the screenshot. If the test is checking the login flow, sign in through the app’s UI; if it only needs an authenticated state, use an application-approved API or session setup where available. The examples below use Python and Selenium WebDriver and assume you are authorized to access the app.

Choose how to reach the authenticated page

The right setup depends on what the test is meant to prove. Selenium’s guidance says not to use browser actions to prepare a test case; where an application provides a supported setup mechanism, using it can avoid repeating login steps. But if the login flow itself is under test, exercise that flow in the browser. See Selenium’s Generating application state.

Use the login UI when authentication is under test

Enter credentials for a dedicated test account, submit the form, and wait for an authenticated-page element. This exercises the login controls and their browser behavior.

Use an approved API or session setup when only page state matters

If your application supports a test API or other authorized session setup, it can establish the state before you load the protected page. A cookie-based setup is application-specific. Selenium requires the browser to be on the cookie’s domain before adding that cookie; see Working with cookies. Cookie setup may not fit every SSO or MFA configuration, so validate it against your app’s identity-provider rules.

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

Log in through the UI and capture the page

Install Selenium in the environment running the test, provide credentials through environment variables or your secret manager, and replace the sample URL and selectors with those used by your app. This example uses Selenium’s Chrome WebDriver and saves a PNG under artifacts/.

import os
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

username = os.environ["TEST_USERNAME"]
password = os.environ["TEST_PASSWORD"]

out = Path("artifacts")
out.mkdir(parents=True, exist_ok=True)

driver = webdriver.Chrome()
try:
    driver.get("https://app.example.test/login")
    wait = WebDriverWait(driver, 15)

    wait.until(
        EC.visibility_of_element_located((By.NAME, "username"))
    ).send_keys(username)
    driver.find_element(By.NAME, "password").send_keys(password)
    driver.find_element(By.CSS_SELECTOR, "button[type='submit']").click()

    # Replace with a stable marker that appears only after authentication.
    wait.until(
        EC.visibility_of_element_located(
            (By.CSS_SELECTOR, "[data-testid='account-home']")
        )
    )

    screenshot_path = out / "protected-page.png"
    if not driver.save_screenshot(str(screenshot_path)):
        raise OSError(f"WebDriver could not save {screenshot_path}")
finally:
    driver.quit()
  • TEST_USERNAME and TEST_PASSWORD must be set in the test environment; do not commit real credentials to source control.
  • The names, button selector, and data-testid are examples, not universal selectors. Choose a marker that is stable and only present in the authenticated state.
  • The explicit wait allows up to 15 seconds for each specified condition. Adjust the timeout to your application and test environment rather than treating this example value as a benchmark.
  • save_screenshot() writes a PNG and returns a Boolean. The code raises an error if the save reports failure.

Set up a test session with a cookie

Use this pattern only if the application provides an authorized way to obtain a valid test session and its cookie rules permit the setup. The cookie name and value below are illustrative; the application determines the required fields, scope, and session behavior.

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

session_cookie_value = "obtain-this-from-your-approved-test-setup"
out = Path("artifacts")
out.mkdir(parents=True, exist_ok=True)

driver = webdriver.Chrome()
try:
    # Establish the cookie's domain before adding it.
    driver.get("https://app.example.test/")
    driver.add_cookie({"name": "session", "value": session_cookie_value})
    driver.get("https://app.example.test/protected")

    wait = WebDriverWait(driver, 15)
    wait.until(
        EC.visibility_of_element_located(
            (By.CSS_SELECTOR, "[data-testid='account-home']")
        )
    )

    screenshot_path = out / "protected-page.png"
    if not driver.save_screenshot(str(screenshot_path)):
        raise OSError(f"WebDriver could not save {screenshot_path}")
finally:
    driver.quit()

Do not assume that inserting one cookie bypasses or correctly reproduces an app’s complete authentication state. For example, the relevant session may depend on cookie attributes, additional state, or an identity-provider flow. Confirm the supported setup with your application rather than guessing cookie fields.

Wait for the content, not just navigation

A completed navigation does not guarantee that a JavaScript-heavy app has finished rendering the content you want to capture. Selenium’s explicit waits poll for a chosen condition until it succeeds or times out. Wait for a visible dashboard container, account heading, or other authenticated-state marker rather than relying on a fixed sleep. Selenium also cautions: “Do not mix implicit and explicit waits.” See Waiting Strategies.

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

Page-load strategy affects when navigation returns, not whether your application’s later JavaScript updates are complete. Selenium documents normal as waiting for document state complete, eager for interactive, and none as not blocking for readiness. If you change the strategy, still use an explicit wait for the actual content to capture; see Browser Options.

Screenshot scope and output

Python’s save_screenshot(path) saves a PNG and reports success as a Boolean. The screenshot area depends on the browser and driver context; do not assume this call produces a full-page image in every setup. Selenium’s API describes screenshot capture as best effort. If your test requires the entire page, verify the behavior with the browser and driver you use rather than inferring it from a successful file save. See the Python WebDriver API.

Rank #4
Diccik 1080P Webcam with Microphone, Full HD Web Camera for Desktop Computer and Laptop USB Computer Camera for PC Pro Streaming Webcam for Zoom/Skype/Teams, Plug and Play PC for Windows &Mac
  • Vivid Full HD 1080P Video Quality: Experience crisp, professional video with the DICCIK 1080p webcam. Delivering 1920 x 1080 resolution at a fluid 30fps, this web camera ensures clear images for every online calling session. Whether you are streaming or recording, it is a reliable computer camera that outperforms standard laptop cameras.
  • Integrated Microphone for Clear Audio: This pc webcam features a built-in noise-reducing mic. Designed as a computer camera with microphone for desktop, it captures your voice naturally while filtering background noise. Perfect for busy home offices, ensuring you are heard loud and clear on Zoom, Skype, and FaceTime.
  • Instant Plug and Play USB Connection: No software or drivers required. Our usb webcam is a true plug and play solution for your PC or Mac. Simply connect the camera for pc to your USB port, and it’s ready in seconds. The flexible clip makes it an easy-to-install monitor camera or desktop camera.
  • Automatic Light Correction for Dim Lighting:Look your best even in low-light environments. This computer camera for desktop automatically adjusts brightness and white balance to match your room's light. From bright offices to dim bedrooms, this streaming webcam ensures a professional look without extra ring lights.
  • Wide Compatibility for Work and Play:A versatile pc camera webcam that works seamlessly with Windows 7/10/11, macOS, and Linux. This webcam for mac and webcam for laptop is fully optimized for Microsoft Teams, Google Meet, and YouTube. An essential camera for computer users across all major operating systems.

For JavaScript WebDriver, takeScreenshot() returns base64-encoded PNG data. The API describes that method and its capture behavior in the JavaScript WebDriver API. Check the result and write or decode it using the file-handling approach appropriate to your test runner.

Troubleshoot common failures

Symptom Likely cause What to check
The wait times out after submitting the form The selector does not match, the login failed, or the authenticated marker never became visible. Confirm the login result, inspect the current page and selector, and choose a marker that appears only in the signed-in state. If the app reports an error, fix the authentication or test data rather than extending the timeout blindly.
The screenshot shows a loading state or incomplete content Navigation returned before client-side rendering finished. Wait for the specific protected-page content needed in the image. Do not substitute a fixed delay for a reliable condition unless the application has no observable readiness signal.
Adding a cookie fails or the app redirects to login The browser was not on the cookie’s domain, or the cookie/session format or identity-provider policy differs from the assumed setup. Navigate to the correct domain first, use the app’s supported test-session mechanism, and verify required cookie scope and state with the app owner.
Screenshot save reports failure The driver did not successfully write the image to the requested path. Check the output directory and permissions, retain the Boolean check, and surface the failure so the test does not silently pass without an artifact.
The image is not full-page The browser/driver capture behavior may cover only the current visible area. Verify the chosen browser and driver’s screenshot behavior. Do not treat a normal screenshot call as a universal full-page guarantee.

Performance, reliability, and safe test setup

  • For a test whose purpose is login validation, keep the UI flow; bypassing it would omit the behavior the test is meant to exercise.
  • For tests focused on protected-page content, an application-approved state setup can avoid repeating UI preparation and make the setup more direct.
  • Use dedicated test identities and keep secrets outside the code. Do not capture a real user’s account or expose credentials or session cookies in logs and saved artifacts.
  • Use stable selectors owned by the application where possible. A selector tied to incidental layout is more likely to break than an explicit test marker.
  • Save artifacts only where the test environment expects them, and ensure the capture is made after the page-specific readiness condition succeeds.
Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.Support on Ko-Fi

Or skip the browser setup

ScreenshotNeo is a screenshot API and MCP server for developers. For an authenticated page, use the API only if the page can be accessed with the supported authentication inputs you are authorized to provide; this one-call example does not itself log in to your application or bypass its access controls. See the ScreenshotNeo documentation for supported parameters.

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://app.example.test/protected 
  -o shot.webp

ScreenshotNeo removes cookie-consent banners, newsletter popups, and chat widgets before capture; each cleanup step can be turned off. Bot checks/CAPTCHAs, blank pages, timeouts, failed loads, and cache hits are not billed, and responses identify the page verdict and billing status in headers. Its MCP server provides take_screenshot, get_page_info, and capture_pdf tools for AI agents and MCP clients. The Free plan includes 1,000 screenshots per month with no card; paid plans start at $5 for 3,000 screenshots.

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

Frequently Asked Questions

Can Selenium take a screenshot before logging in?

Yes, but it will capture whatever the browser can access in its current state, such as the login page or an access-denied page; it does not make a protected page authenticated.

Does `save_screenshot()` create a full-page image?

Not necessarily. The captured area can depend on the browser and driver context, so verify full-page behavior in your chosen setup.

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

Can I use this approach with SSO or MFA?

The workflow depends on the app and identity provider. UI login may require handling the provider’s flow, while cookie setup is not established as compatible with every SSO or MFA configuration.

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.