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

Set the browser window size explicitly with driver.set_window_size(width, height), then check the page’s actual CSS viewport before taking the screenshot. The requested browser-window size, the page viewport and the saved image’s pixel dimensions are separate measurements, so verify the one your test or output actually depends on.

Set the window size before loading the page

For a repeatable Selenium screenshot, choose dimensions, apply them to the browser window, inspect the resulting dimensions, and then navigate to the page. Setting the size before navigation matters when the site’s responsive layout should load at your target width.

This example uses Chrome and a target browser-window size of 1280 × 900 pixels. Those numbers are an example, not a guarantee that the page viewport or PNG will have the same dimensions.

from selenium import webdriver

TARGET_WIDTH = 1280
TARGET_HEIGHT = 900
URL = "https://example.com"

options = webdriver.ChromeOptions()
# For headless runs, use the headless syntax supported by your installed Chrome version.
# For example, add the appropriate options.add_argument(...) here.

driver = webdriver.Chrome(options=options)
try:
    driver.set_window_size(TARGET_WIDTH, TARGET_HEIGHT)

    # These are browser-window dimensions reported by WebDriver.
    print("WebDriver window:", driver.get_window_size())
    print("WebDriver window rectangle:", driver.get_window_rect())

    # These are the page's CSS viewport dimensions.
    viewport = driver.execute_script(
        "return {width: window.innerWidth, height: window.innerHeight}"
    )
    print("CSS viewport:", viewport)

    driver.get(URL)
    driver.save_screenshot("screenshot.png")
finally:
    driver.quit()

The Selenium Python Chromium WebDriver API documents set_window_size(width, height) in pixels, along with get_window_size() and get_window_rect() for inspecting the result. Selenium’s window guide also demonstrates setting a window size in Python. These are WebDriver window controls; they do not establish the CSS viewport size by themselves. Selenium Python Chromium WebDriver API · Selenium: Working with windows and tabs

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
  1. Decide which dimensions matter to your use case: a browser-window size, the page’s CSS viewport, or the final image’s pixel dimensions.
  2. Start the intended browser and mode. If running headless, use syntax supported by the installed browser version rather than assuming all Chrome versions accept the same option.
  3. Call driver.set_window_size(width, height) before navigating when the page should render at the target responsive width.
  4. Inspect driver.get_window_size() or driver.get_window_rect(), then read window.innerWidth and window.innerHeight if the page layout depends on its CSS viewport.
  5. Navigate, wait for the page state and visual assets your capture requires, and save the screenshot.
  6. If exact PNG dimensions matter, inspect the resulting file in the same environment that will run the capture.

Know which dimensions Selenium is reporting

“Window size” can refer to different things in a screenshot workflow. A reliable test records the relevant measurements separately instead of assuming a size request controls every layer.

Measurement or control What it tells or controls Important qualification
set_window_size(width, height) Requests the browser window’s width and height in pixels. Check the resulting values with get_window_size() or get_window_rect().
window.innerWidth and window.innerHeight The CSS viewport dimensions reported to page JavaScript; these are useful for checking responsive breakpoints. A requested outer browser-window size does not prove that the CSS viewport matches it.
save_screenshot(path) Saves a PNG screenshot of the current top-level browsing context. The WebDriver standard defines screenshot capture in terms of the visual viewport. Verify the image itself if its exact pixel dimensions matter.
PNG pixel dimensions The width and height of the saved image file. Do not infer them from the requested window dimensions; inspect the generated PNG in the target environment.

The Selenium Python Remote WebDriver API documents save_screenshot() and get_screenshot_as_file() for saving PNG files, and get_screenshot_as_png() for retrieving PNG bytes. The WebDriver standard describes screenshots as captures of the visual viewport of the top-level browsing context. Selenium Python Remote WebDriver API · W3C WebDriver specification

Validate the saved PNG when file dimensions matter

If another system requires a particular image size, check the PNG rather than relying on a window-size request. A PNG file stores its dimensions near the start of the file; this small standard-library check reads them after Selenium saves the screenshot.

import struct

with open("screenshot.png", "rb") as image_file:
    header = image_file.read(24)

if len(header) < 24 or header[:8] != b"x89PNGrnx1an":
    raise ValueError("The output is not a valid PNG file")

pixel_width, pixel_height = struct.unpack(">II", header[16:24])
print(f"PNG dimensions: {pixel_width} × {pixel_height} pixels")

This validation reports the file’s pixel dimensions; it does not change the browser viewport or make two captures visually identical. If the output size differs from what your pipeline expects, adjust the browser or emulation setup for the target environment and verify the generated file again.

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

Make repeated captures more comparable

A fixed window size removes one source of variation, but it is not a bit-for-bit reproducibility guarantee across machines. Browser chrome, the operating-system window manager, headless implementation, device scale, fonts and browser version can affect rendered output. For repeatable runs, record the browser and driver versions, operating system or container, headed/headless mode, requested window dimensions, measured viewport, and any device-scale or emulation settings.

  • Set dimensions explicitly. Do not rely on the desktop’s current resolution or a maximize operation when the test needs a defined size.
  • Measure after setting. Log WebDriver’s reported window values and the CSS viewport values relevant to the page.
  • Navigate at the intended width. Responsive pages may choose layout based on the viewport available during loading.
  • Control page readiness for your site. A screenshot taken before required content, fonts or images appear can differ even when the viewport is unchanged. Wait for the condition your application needs before capture.
  • Validate the artifact. Inspect the PNG dimensions—and, when visual equality matters, compare the actual images in the same runtime environment.

The API documentation establishes the size and screenshot methods, but it does not promise that a requested outer window size will always equal either the CSS viewport or final PNG pixel dimensions. Nor do the cited sources establish a cross-browser recipe that guarantees identical rendered pixels on different hosts.

Use Chromium emulation only when you need viewport-level control

For Chromium-only workflows that need direct device metrics or viewport emulation, Chrome DevTools Protocol (CDP) offers Emulation.setDeviceMetricsOverride. Its parameters include width, height, mobile emulation and device scale factor; the protocol reference says the command overrides values including window.innerWidth, window.innerHeight and related CSS media-query results.

CDP is a browser-specific option, not a portable WebDriver command. Use it when that Chromium dependency is acceptable and ordinary window sizing does not provide the control you need. Chrome DevTools Protocol: Emulation domain

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

Troubleshoot inconsistent Selenium screenshots

The CSS viewport is smaller or larger than the requested window

Cause: WebDriver’s window dimensions and the page’s CSS viewport are different measurements; browser chrome and the environment may affect the usable area.

Fix: Print driver.get_window_size() and window.innerWidth/window.innerHeight separately. If the responsive layout is the concern, treat the JavaScript viewport measurement as the relevant check. For Chromium-specific viewport emulation, consider CDP and document that browser dependency.

The PNG is not the dimensions you requested

Cause: A window-size request alone does not guarantee matching screenshot pixel dimensions.

Fix: Read the PNG dimensions after capture and confirm the window, viewport, browser mode and device-scale settings in the target environment. Do not compensate by assuming a fixed conversion between the three measurements.

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

The page uses a different responsive layout between runs

Cause: The page may have been loaded before the intended dimensions were applied, or the run may not be using the same viewport or environment.

Fix: Set the size before driver.get(), log the CSS viewport, and keep the browser mode and runtime details consistent. If necessary, reload after changing dimensions so the page can render at the intended size.

The screenshot is blank, incomplete or missing visual assets

Cause: Capture may occur before the page or the specific visual content your test needs is ready.

Fix: Wait for an application-specific readiness condition before saving the screenshot. A fixed viewport does not control when a page finishes rendering.

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

A headless run behaves differently from a headed run

Cause: Headless implementation and browser version are among the environmental factors that can affect rendered output; headless option syntax may also depend on the installed Chrome version.

Fix: Use the option syntax supported by the browser installed in the environment, log whether the run is headless, and validate the viewport and PNG dimensions there rather than assuming desktop results transfer exactly.

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

Or skip the browser setup

If you need a screenshot service rather than a browser managed by your script, ScreenshotNeo is a website screenshot API and MCP server for developers. For consistent captures, it accepts viewport sizes and device presets, with retina scaling also available. A GET request returns an image or PDF; see the ScreenshotNeo API documentation for request options.

Here is the one-call Python version using the documented API base and parameter pattern:

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
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)

Equivalent cURL and Node.js calls:

curl -G "https://api.screenshotneo.com/v1/shot" -d access_key=YOUR_API_KEY --data-urlencode url=https://stripe.com -o shot.webp
const q = new URLSearchParams({ access_key: 'YOUR_API_KEY', url: 'https://stripe.com' });
const res = await fetch(`https://api.screenshotneo.com/v1/shot?${q}`);
  • Before capture, ScreenshotNeo accepts cookie or consent banners like a visitor and removes 60+ known consent platforms, newsletter popups and chat widgets; each of those steps can be turned off.
  • Bot checks or CAPTCHAs, blank pages, timeouts, failed loads and cache hits are not billed. Responses include X-Page-Verdict and X-Billed headers to identify the page result and billing status.
  • Its MCP server provides take_screenshot, get_page_info and capture_pdf tools for Claude, Cursor and other MCP clients.
  • The Free plan includes 1,000 screenshots per month without a card; paid plans start at $5 for 3,000 shots. Every feature is available on every plan.

Sign up for ScreenshotNeo’s free plan to get 1,000 screenshots a month with no card.

FAQ

Can Selenium save screenshot bytes instead of writing directly to a file?

Yes. Selenium’s Remote WebDriver API provides get_screenshot_as_png(), which returns PNG bytes; use save_screenshot(path) or get_screenshot_as_file(path) when you want Selenium to save a PNG file. Selenium Python Remote WebDriver API

Is CDP viewport emulation portable to Firefox or other browsers?

No. The cited emulation mechanism is part of Chrome DevTools Protocol and is appropriate when a Chromium-specific dependency is acceptable; use WebDriver’s window sizing when portability is the priority.

Frequently Asked Questions

Can Selenium save screenshot bytes instead of writing directly to a file?

Yes. Selenium’s Remote WebDriver API provides get_screenshot_as_png() for PNG bytes, as well as methods to save a PNG file.

Free tools Windows power users keep installed

One-click scans. No signup required.

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

Is CDP viewport emulation portable to Firefox or other browsers?

No. This emulation mechanism is part of Chrome DevTools Protocol and is Chromium-specific.

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.