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

Some links on this page are affiliate links: if you buy through them we may earn a commission, at no extra cost to you.

With a current Selenium Python WebDriver, set the browser window after creating the session:

driver.set_window_size(1024, 768)

The two arguments are width and height in pixels. The values are examples, not universal requirements; choose dimensions that match the layout, breakpoint, or test case you need. PhantomJS requires a prominent qualification: its official project page states, “Important: PhantomJS development is suspended until further notice.” Use the common sizing call only when maintaining a historical PhantomJS stack, and use a maintained browser for new automation.

Set a Selenium window size in Python

Create a WebDriver session, call set_window_size(width, height), and optionally read the result with get_window_size(). A complete example using a maintained browser is:

What’s actually slowing this PC down?

Pick the symptom - the matching free tool is one click away.

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

# Create the session using the browser and driver setup used by your project.
driver = webdriver.Chrome()

try:
    driver.set_window_size(1024, 768)
    print(driver.get_window_size())
    driver.get("https://example.com")
finally:
    driver.quit()

The current Selenium Python API documents the dimensions as pixel values and provides a current-window default. The documented API also accepts an optional windowHandle argument. In ordinary code, switching to the target tab before resizing is clearer:

handle = driver.current_window_handle
driver.switch_to.window(handle)
driver.set_window_size(1024, 768)

Do not treat 1024 × 768 as a Selenium requirement. It is simply a documented example. Use a desktop size, a narrow mobile-like size, or a matrix of sizes that represents the pages and breakpoints your test covers.

What width and height control

set_window_size(width, height) requests the outer browser window dimensions. Browser chrome, operating-system decorations, and the browser's own layout can affect the content viewport that a page ultimately receives. For responsive tests, verify the dimensions your session reports and, when necessary, inspect the page's viewport from JavaScript as well.

requested = {"width": 1280, "height": 900}
driver.set_window_size(requested["width"], requested["height"])
actual = driver.get_window_size()
print("requested:", requested)
print("reported:", actual)
print("viewport:", driver.execute_script(
    "return {width: window.innerWidth, height: window.innerHeight};"
))

If the reported size differs from what you requested, record the browser, driver, operating system, headless mode, and Selenium version with the failure. The API call is standardized, but this article does not claim that every combination honors dimensions identically.

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

Resize, move, or set the entire window rectangle?

Operation Python call Use it for
Resize driver.set_window_size(width, height) Changing width and height of the current window.
Read size driver.get_window_size() Checking the width and height reported by WebDriver.
Move driver.set_window_position(x, y) Changing the window's screen coordinates without making a size request.
Set rectangle driver.set_window_rect(x, y, width, height) Setting position and size together where the W3C-compatible browser supports it.

Moving a window does not make it wider, and changing its size does not select a responsive breakpoint by itself. Use the operation that matches the diagnosis you are making.

Use a size in a responsive test

Keep dimensions with the test data instead of scattering literals through the suite:

from selenium import webdriver

sizes = [
    (375, 812),    # narrow layout case
    (768, 1024),   # tablet-like case
    (1440, 900),   # wide desktop case
]

driver = webdriver.Chrome()
try:
    for width, height in sizes:
        driver.set_window_size(width, height)
        driver.get("https://example.com")
        print(width, height, driver.get_window_size())
        # Add assertions for the layout at this size here.
finally:
    driver.quit()

Choose cases from your product's supported breakpoints. A single arbitrary size can miss an intermediate layout change, while testing every possible pixel is unnecessary.

Headless sessions and viewport verification

Headless execution can have different window-management behavior from headed execution. If your browser supports a command-line window-size option, configure it in the browser's options as well as using WebDriver's window API, then verify both get_window_size() and window.innerWidth. Keep the browser and driver versions aligned according to the setup guidance for that browser. Do not infer cross-platform equivalence from one successful run.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
from selenium import webdriver
from selenium.webdriver.chrome.options import Options

options = Options()
options.add_argument("--headless=new")
options.add_argument("--window-size=1280,900")
driver = webdriver.Chrome(options=options)
try:
    driver.set_window_size(1280, 900)
    print(driver.get_window_size())
finally:
    driver.quit()

The exact headless option is browser-specific. If a remote grid or container controls the browser, its display configuration can also affect the result.

PhantomJS: what still applies and what does not

PhantomJS describes itself as a JavaScript-scriptable headless browser, but its official home page carries the notice: “Important: PhantomJS development is suspended until further notice.” That status makes it a legacy maintenance concern, not a current browser choice for new Selenium projects.

The resize operation is the part that maps directly to the documented Selenium API:

driver.set_window_size(1024, 768)

Do not copy a historical constructor such as an old PhantomJS-specific setup and assume it is valid with current Selenium. The available current material documents the sizing method, but it does not establish a current PhantomJS constructor recipe or a compatibility matrix covering PhantomJS versions, Selenium releases, operating systems, and drivers. If you must maintain an existing PhantomJS script:

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
  1. Record the exact Python, Selenium, PhantomJS, and operating-system versions already used.
  2. Run the existing session setup unchanged in an isolated environment.
  3. Call set_window_size only after the session has been created.
  4. Read back get_window_size() and compare the page's actual viewport before changing tests.
  5. Plan migration to a maintained browser rather than treating a passing legacy run as evidence of current support.

Old Selenium 2-era references show examples such as driver.set_window_size(800,600). Those examples explain the historical API and pixel arguments; they are not current installation guidance. Selenium's Python changelog records removal of the deprecated desired_capabilities property in Selenium 4.17.0, another reason to review old initialization snippets rather than paste them into a current project.

Common failures and fixes

“Window size” is accepted but the layout does not change

Check the content viewport, not only the requested outer size. Print driver.get_window_size() and window.innerWidth. If the page uses a fixed layout, a zoom setting, or a responsive breakpoint outside your chosen values, changing the window will not produce the visual change you expect.

The returned size is different

Repeat the measurement after the session is fully created and note headed versus headless mode, remote execution, operating system, and browser version. Use set_window_rect only when you need position and size together and the browser supports that W3C operation.

The call raises an unknown-command or unsupported-operation error

Confirm that the session is a real WebDriver session and that the browser driver matches the browser. Remote grids and legacy engines may expose a narrower window-management implementation. Capture the complete exception and session capabilities before substituting unrelated options.

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

A tab was resized other than the one under test

Window operations apply to the current window by default. Switch explicitly with driver.switch_to.window(handle), then call the resize method. Keep handles in a list if the test opens more than one tab.

An old PhantomJS example fails during startup

That failure is usually a legacy setup or compatibility issue, not a different width syntax. PhantomJS development is suspended, and no current compatibility matrix is established here. Preserve the historical environment only for maintenance and migrate new coverage to a maintained browser.

Performance, reliability, and cost considerations

Resizing is a local WebDriver command; the expensive part of a screenshot or visual test is usually navigation, page rendering, waiting, and image comparison. Reuse a session when isolation rules allow it, resize immediately before the case that needs the dimensions, and avoid needless navigation between size checks. For reliable assertions, wait for the page state your test actually needs instead of assuming that a resize means the page has finished reflowing.

When running many dimensions, report the requested and observed sizes with every failure. This makes a viewport problem distinguishable from a CSS or application defect. No universal timing or cross-platform success rate is established for these operations, so measure in the browser and environment you support.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
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 your goal is a clean website image or PDF rather than interactive browser assertions, ScreenshotNeo provides a single HTTP request. It accepts consent banners before capture and removes more than 60 known consent platforms, newsletter popups, and chat widgets; each cleanup step can be disabled. Bot checks or CAPTCHAs, blank pages, timeouts, failed loads, and cache hits are not billed, and the response identifies the result with X-Page-Verdict and X-Billed headers. An MCP server exposes take_screenshot, get_page_info, and capture_pdf to Claude, Cursor, and other MCP clients.

See the ScreenshotNeo API documentation for all options. A basic Python call is:

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)

The equivalent cURL request is:

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

And in 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}`);

ScreenshotNeo also supports full-page captures with lazy images loaded, CSS-element capture, dark mode, device presets or custom viewports, retina scale, PDF paper and page-range controls, custom CSS and JavaScript, clicks, selector waits, delays, network-idle waits, request blocking, headers, cookies, user agents, authorization, timezone, geolocation, transparent backgrounds, resizing, chosen cache TTLs, signed image links, asynchronous jobs with signed webhooks, bulk capture of up to 100 URLs per call, a usage API, and an OpenAPI specification. Parameter names used by other screenshot APIs also work for easier migration.

The Free plan includes 1,000 screenshots per month with no card. Paid plans start at $5 for 3,000 shots; every feature is available on every plan, and yearly billing provides two months free. Sign up for the free plan to try it without a card.

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

Frequently Asked Questions

Does Selenium resize the viewport or the whole browser window?

The method requests the WebDriver window width and height. Verify the resulting content viewport separately with get_window_size() and window.innerWidth when responsive behavior matters.

Can I pass decimal dimensions?

Use integer pixel values for width and height. Keep the values explicit in test data so failures identify the intended breakpoint.

Should a new project still use PhantomJS?

No recommendation for new work is made here: PhantomJS development is suspended. Use a maintained browser and retain PhantomJS only as a version-pinned legacy environment that you are actively migrating.

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.

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