How to Capture a Screenshot of a Responsive Website at Tablet Width with Selenium
Set a deliberate tablet-sized viewport, verify the page width, and save a reproducible Selenium screenshot in Python or Node.js.
To capture a responsive website at a chosen tablet width with Selenium, configure the browser, open the page, verify the page’s CSS viewport width, and save a screenshot. For a desktop-style responsive layout, resize the browser window. For Chrome tests that also need mobile emulation, set device metrics before creating the driver. There is no single universal tablet width: choose one that matches the breakpoint or device scenario you want to check.
1. Choose what “tablet width” means
A browser window size and a CSS viewport size are related but not always identical. Browser and operating-system chrome can reduce the space available to the page. A desktop-window resize is a straightforward way to exercise responsive CSS at a chosen width. Chrome mobile emulation is a separate, browser-specific setup that can also change screen metrics and device pixel ratio.
Before capturing, record the intended width and height, orientation, pixel ratio, browser and driver versions, and whether mobile emulation is enabled. Treat sample dimensions as project choices, not a tablet standard.
| Goal | Setup | What to verify |
|---|---|---|
| Check responsive CSS at a chosen width | Set the browser window size | window.innerWidth after navigation |
| Approximate a mobile device in Chrome | Enable Chrome mobile emulation with device metrics | Viewport width, screen metrics and pixel ratio |
| Check a particular breakpoint | Choose a width on the relevant side of the breakpoint, then repeat on the other side if useful | The actual CSS viewport width and resulting layout |
Selenium’s Python API documents window sizing and screenshot saving. Chrome’s mobile emulation options configure device metrics. Device-metrics overrides can affect window.screen.width, window.innerWidth and device-width media query results, so use the setup that matches the behavior you intend to test. Selenium Python WebDriver API, Selenium JavaScript Chrome options, Chrome DevTools device metrics.
2. Capture a responsive screenshot with Selenium in Python
Install Selenium in your Python environment with python -m pip install selenium. Use a compatible Chrome and driver setup for your installed Selenium version. This example resizes a desktop browser window; the dimensions are illustrative. It checks the resulting CSS viewport and fails clearly if the screenshot API reports that the file was not saved.
from pathlib import Path
from selenium import webdriver
url = "https://example.com"
width = 900
height = 1100
output = Path("screenshots/tablet-view.png")
output.parent.mkdir(parents=True, exist_ok=True)
driver = webdriver.Chrome()
try:
driver.set_window_size(width, height)
driver.get(url)
viewport = driver.execute_script(
"return {width: window.innerWidth, height: window.innerHeight};"
)
print(f"Requested window: {width} x {height}")
print(f"CSS viewport: {viewport['width']} x {viewport['height']}")
saved = driver.save_screenshot(str(output))
if not saved:
raise RuntimeError(f"Selenium did not save the screenshot to {output}")
print(f"Saved {output}")
finally:
driver.quit()
set_window_size(width, height) sets browser window dimensions. The screenshot represents the current page view. If the exact CSS breakpoint matters, use the measured window.innerWidth as your check; do not assume the outer window width equals it. Selenium’s save_screenshot(path) returns a Boolean, so check it and save to a known writable path. Python WebDriver API: window size and screenshot methods.
3. Capture at tablet dimensions with Chrome mobile emulation
Use mobile emulation when the scenario requires Chrome’s emulated device metrics as well as a chosen viewport. Configure it before building the driver. This Python example uses custom dimensions and a pixel ratio of 1; change those values to match the scenario and your installed Selenium and ChromeDriver versions.
from pathlib import Path
from selenium import webdriver
url = "https://example.com"
output = Path("screenshots/tablet-emulated.png")
output.parent.mkdir(parents=True, exist_ok=True)
options = webdriver.ChromeOptions()
options.add_experimental_option(
"mobileEmulation",
{
"deviceMetrics": {
"width": 900,
"height": 1100,
"pixelRatio": 1,
}
},
)
driver = webdriver.Chrome(options=options)
try:
driver.get(url)
viewport = driver.execute_script(
"return {width: window.innerWidth, height: window.innerHeight, "
"screenWidth: window.screen.width, screenHeight: window.screen.height};"
)
print(f"Emulated metrics: {viewport}")
if not driver.save_screenshot(str(output)):
raise RuntimeError(f"Selenium did not save the screenshot to {output}")
finally:
driver.quit()
Chrome mobile emulation is not the same as resizing a desktop browser. Select the setup that corresponds to the test you need, and confirm the effective dimensions in the browser. Selenium’s JavaScript documentation describes custom emulation dimensions, pixel ratio and preconfigured device names; exact options can vary by language binding and version. Selenium JavaScript Chrome options.
4. Node.js example
Install the Selenium JavaScript binding with npm install selenium-webdriver and use a compatible Chrome and ChromeDriver setup. This example enables custom mobile emulation, captures the current page view, writes the PNG and always quits the driver.
const fs = require('node:fs');
const path = require('node:path');
const { Builder } = require('selenium-webdriver');
const chrome = require('selenium-webdriver/chrome');
async function capture() {
const output = path.join('screenshots', 'tablet-view.png');
fs.mkdirSync(path.dirname(output), { recursive: true });
const options = new chrome.Options().setMobileEmulation({
deviceMetrics: { width: 900, height: 1100, pixelRatio: 1 }
});
const driver = await new Builder()
.forBrowser('chrome')
.setChromeOptions(options)
.build();
try {
await driver.get('https://example.com');
const viewport = await driver.executeScript(
'return {width: window.innerWidth, height: window.innerHeight}'
);
console.log('CSS viewport:', viewport);
const image = await driver.takeScreenshot();
fs.writeFileSync(output, image, 'base64');
console.log(`Saved ${output}`);
} finally {
await driver.quit();
}
}
capture().catch(error => {
console.error(error);
process.exitCode = 1;
});
This uses Selenium’s JavaScript screenshot API and Chrome’s mobile emulation options. Confirm that the installed binding and ChromeDriver accept the configuration. If you only need a desktop-style responsive viewport, use the JavaScript binding’s browser window sizing API and still inspect window.innerWidth.
5. Make captures reproducible
- Choose the target scenario. Write down the CSS width, height, orientation, browser and whether mobile emulation is part of the test.
- Set dimensions before capture. For emulation, configure device metrics before driver creation. For window resizing, set the size before taking the screenshot.
- Navigate and verify. Read
window.innerWidthand, when useful,window.innerHeightandwindow.screen.width. - Wait for the page state you need. Selenium navigation completion does not guarantee that every image or late-loading component has finished. Wait for a meaningful page condition when the screenshot depends on it.
- Save and check. Create the destination directory, check the Python Boolean result, and make sure Node.js finishes writing the file.
- Clean up the browser. Call
quit()in afinallyblock so failures do not leave a driver process running.
If you compare screenshots over time, keep dimensions, emulation mode, browser version and page readiness conditions consistent. A viewport screenshot captures the current view; do not assume it is a full-page capture. The sources for this workflow document current-context capture and device/window sizing, not a universal Selenium full-page method.
6. Troubleshooting
| Symptom | Likely cause | Fix |
|---|---|---|
| The layout does not match the expected tablet breakpoint | The page’s CSS viewport differs from the requested outer window size | Print window.innerWidth after navigation and adjust the window dimensions or use device emulation. Base breakpoint checks on the measured CSS width. |
| The screenshot has unexpected dimensions or density | Mobile emulation and desktop window resizing use different metrics; pixel ratio also affects device emulation | Record the chosen mode and pixel ratio, inspect effective browser metrics, and use the same configuration for each run. |
| Chrome fails to start or the session cannot be created | Browser, driver and Selenium versions or environment setup are incompatible | Check the versions and Selenium setup guidance for the installed binding; update or configure a compatible driver and browser. |
| The screenshot file is missing | The parent directory does not exist, the process cannot write there, or the save call failed | Create the directory first, use an absolute path while diagnosing, check Python’s Boolean return value, and inspect the process’s write permissions. |
| The capture shows a loader or incomplete content | Some page resources or application rendering finish after navigation returns | Wait for a specific element or application-ready condition that matters to the page, then capture. Avoid relying on a fixed delay when a reliable condition is available. |
| Mobile emulation options are rejected | The option syntax or support differs in the installed Selenium binding or Chrome version | Check the versioned API for your binding and confirm the ChromeDriver compatibility. Keep emulation configuration in Chrome options before driver creation. |
| The image is not a full-page screenshot | The standard capture is of the current view | Confirm whether viewport capture is sufficient. If you require the entire document, choose and verify a full-page method supported by your browser and binding. |
7. Performance, reliability and cost
Selenium starts and controls a browser, so each capture depends on browser startup, page loading and the machine or runner where it runs. For repeatable results, reuse a deliberate viewport configuration, wait on page conditions instead of arbitrary long sleeps, and always close the driver. Parallel captures need enough browser and machine capacity; more simultaneous sessions can increase resource use and make timing less predictable.
There is no universal runtime or cost figure for this workflow: it depends on the page, browser environment and infrastructure. Account for the cost of the machine or hosted browser environment you use, plus maintenance of compatible browser and driver versions. A service can avoid managing browser setup, but compare its behavior and billing rules against your capture requirements.
8. Or skip the browser setup
ScreenshotNeo is a website screenshot API and MCP server. For a one-call capture, create an API key and request an image. The URL and key below are examples; replace the target URL and use your own key. See the ScreenshotNeo API documentation for request options and response details.
curl -G "https://api.screenshotneo.com/v1/shot" -d access_key=YOUR_API_KEY --data-urlencode url=https://example.com -o shot.webp
import requests
r = requests.get("https://api.screenshotneo.com/v1/shot", params={"access_key": "YOUR_API_KEY", "url": "https://example.com"}, timeout=90)
open("shot.webp", "wb").write(r.content)
const q = new URLSearchParams({ access_key: 'YOUR_API_KEY', url: 'https://example.com' });
const res = await fetch(`https://api.screenshotneo.com/v1/shot?${q}`);
if (!res.ok) throw new Error(`Screenshot request failed: ${res.status}`);
await require('node:fs/promises').writeFile('shot.webp', Buffer.from(await res.arrayBuffer()));
ScreenshotNeo lets you set viewport dimensions and offers device presets, so you can choose a tablet-sized capture configuration. Cookie banners, newsletter popups and chat widgets are removed before the shot; bot checks, blank pages and failed loads are never billed. Its MCP server lets AI agents take screenshots. The free plan includes 1,000 screenshots a month with no card, and paid plans start at $5 for 3,000. Every feature is on every plan.
Sign up for 1,000 free screenshots a month, with no card required.
9. Frequently asked questions
Is 900 pixels the standard tablet width?
No. It is an illustrative value. Use the width that matches the breakpoint or device scenario your project needs to cover.
Should I use mobile emulation for every responsive check?
No. A window resize is enough when the goal is to exercise CSS at a selected width. Use emulation when the test also needs Chrome’s device metrics.
Does Selenium’s screenshot call save a full webpage?
The examples capture the current browser view. A full-document capture is a separate requirement; select a method supported by your browser and Selenium binding and verify its output dimensions.
Why record pixel ratio and orientation?
They are part of the emulated device scenario and help make repeated captures comparable, especially when comparing image dimensions or responsive rendering.


