ScreenshotNeo

BlogHow-to

How to Capture Mobile-Width Screenshots of Indian Ecommerce Websites with Selenium

Use Selenium and Chrome mobile emulation to capture Indian ecommerce pages at a chosen mobile viewport. Configure the profile, wait for the right page state, and save a reproducible screenshot.

By the ScreenshotNeo team4 October 20269 min read

To capture an Indian ecommerce page at a mobile width with Selenium, configure Chrome’s mobile emulation when creating the driver, open the page, wait for the state you want to document, then save the current browser screenshot. A mobile emulation profile can set CSS viewport width and height and device pixel ratio (DPR). A normal narrow browser window is useful for testing responsive layout, but it is not the same configuration as mobile emulation.

The example below uses a 390 × 844 CSS-pixel viewport and DPR 3 as an explicitly chosen test profile. Those values are examples, not a claim about the most common Indian phone or shopper. There is no single India-wide viewport recommendation established by the cited documentation. Choose profiles that match your own test plan and record them with the image.

1. Choose what the screenshot should represent

Decide these details before writing the capture script:

  • Emulation or narrow desktop: use Chrome mobile emulation when mobile behavior matters. It configures device metrics and mobile behavior; set_window_size alone changes the browser window dimensions.
  • Viewport: specify width and height in CSS pixels. The viewport width affects responsive breakpoints; height determines how much content appears in a viewport screenshot.
  • DPR: choose a device pixel ratio for resolution-sensitive rendering and image selection. A CSS viewport width by itself does not fully describe the profile.
  • Capture scope: Selenium’s ordinary driver screenshot captures the current window’s visible browser content. A full-page image is a different deliverable and needs a separate capture method.
  • Page state: say whether the image represents initial load, a settled page, a dismissed consent dialog, a selected variant, or another interaction state.

Chrome’s documentation distinguishes viewport screenshots from full-size page screenshots and explains DPR in its Device Mode guide. Selenium documents its screenshot and window-sizing methods in the Python WebDriver API.

2. Install Selenium and prepare Chrome

Install Selenium in the Python environment that will run the script:

python -m pip install selenium

Use a Chrome installation available to the process. Selenium Manager can manage drivers in supported setups; otherwise ensure the ChromeDriver major version matches the installed Chrome major version. See Selenium’s Chrome browser documentation. In a container or remote machine, also ensure the browser has a writable output directory and any required runtime libraries.

3. Capture a mobile-width screenshot with Python

This runnable example enables Chrome mobile emulation with custom device metrics, navigates to a sample Indian ecommerce URL, waits for the document to finish loading, and writes a PNG. Replace the URL and, when possible, replace the generic load wait with a wait for the specific product or page state your capture requires.

from pathlib import Path
from selenium import webdriver
from selenium.webdriver.chrome.options import Options
from selenium.webdriver.support.ui import WebDriverWait

URL = "https://example.in/"
OUTPUT = Path("captures/example-in-390x844-dpr3.png")

options = Options()
options.add_experimental_option("mobileEmulation", {
    "deviceMetrics": {
        "width": 390,
        "height": 844,
        "pixelRatio": 3.0,
    }
})

OUTPUT.parent.mkdir(parents=True, exist_ok=True)
driver = webdriver.Chrome(options=options)
try:
    driver.set_page_load_timeout(60)
    driver.get(URL)
    WebDriverWait(driver, 30).until(
        lambda browser: browser.execute_script(
            "return document.readyState"
        ) == "complete"
    )
    if not driver.save_screenshot(str(OUTPUT)):
        raise OSError(f"Could not save screenshot to {OUTPUT}")
finally:
    driver.quit()

document.readyState == "complete" only indicates the document load state. It does not guarantee that a product image, client-rendered content, recommendation widget, or lazy-loaded section is ready. Add a meaningful explicit wait for the page you are capturing.

Wait for the relevant content

For a product detail page, wait for a stable product selector rather than sleeping for an arbitrary duration:

from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions as EC

WebDriverWait(driver, 30).until(
    EC.visibility_of_element_located((By.CSS_SELECTOR, "main .product"))
)

Replace the selector with one verified for the target page. If you need a specific state such as a chosen size or an open menu, perform that interaction and wait until the state is visible before saving.

4. Select a device profile responsibly

ChromeDriver supports both named device profiles and custom emulation metrics. A preset can be convenient when its exact device profile is appropriate; custom metrics make the width, height, and DPR explicit and easy to reproduce. The available presets and supported settings can vary with ChromeDriver versions, so check the current ChromeDriver mobile emulation documentation.

For comparisons, keep the profile fixed across sites or runs. Store a useful filename such as site-page-width-height-dpr-state.png, and keep the exact viewport, DPR, browser version, URL, and capture-state notes in your test record. Do not present a single chosen profile as representative of all Indian shoppers. For market coverage, select profiles using your own analytics or testing requirements.

5. Viewport screenshots versus full-page screenshots

driver.save_screenshot(...) captures the current window. It is appropriate when the intended artifact is the visible mobile viewport. Do not label it a full-page screenshot if content below the fold is absent.

For a full-page capture, use a method specifically designed to capture beyond the viewport, such as Chrome DevTools’ full-size screenshot workflow or an appropriate browser-specific DevTools command. Selenium’s standard screenshot call does not itself promise a full-page image. Full-page capture can also change how sticky headers and lazy-loaded content appear, so decide whether to scroll the page to trigger content before capturing and document that choice.

6. JavaScript Selenium example

If the project uses Selenium’s JavaScript bindings, configure Chromium mobile emulation on the Chrome options before creating the driver. This example writes the screenshot bytes to a PNG file.

const { Builder } = require('selenium-webdriver');
const chrome = require('selenium-webdriver/chrome');
const fs = require('node:fs/promises');

(async () => {
  const options = new chrome.Options();
  options.setMobileEmulation({
    deviceMetrics: { width: 390, height: 844, pixelRatio: 3.0 }
  });
  const driver = await new Builder()
    .forBrowser('chrome')
    .setChromeOptions(options)
    .build();

  try {
    await driver.get('https://example.in/');
    await driver.wait(async () => {
      return await driver.executeScript('return document.readyState') === 'complete';
    }, 30000);
    const png = await driver.takeScreenshot();
    await fs.mkdir('captures', { recursive: true });
    await fs.writeFile('captures/example-in-390x844-dpr3.png', png, 'base64');
  } finally {
    await driver.quit();
  }
})().catch(error => {
  console.error(error);
  process.exitCode = 1;
});

The Selenium JavaScript Chromium options API documents setMobileEmulation and the preset-device and custom-metric approaches in its Chromium Options reference.

7. Capture options and practical choices

Choice Use it for Watch for
Custom width, height, DPR Repeatable project-specific viewport tests Record all three values; width alone is incomplete.
Named device preset Convenient emulation of a supported Chrome device profile Confirm the preset exists in the installed ChromeDriver version.
Mobile behavior and touch Testing behavior that depends on mobile emulation A resized desktop window does not configure the same emulation behavior.
Viewport image Visual review of the first screen or a particular scroll position Only the visible window is captured.
Full-page image Reviewing content from top to bottom in one artifact Requires a full-page-capable capture approach; lazy content may need preparation.
Explicit wait Capturing a defined page or interaction state Choose a selector/state that is meaningful and stable for the target site.
Page-load timeout Preventing navigation from hanging indefinitely A timeout does not prove the page is unusable; inspect and decide whether partial content is meaningful.

Keep the capture state consistent when comparing pages: viewport dimensions, DPR, browser configuration, scroll position, and interactions can all affect the resulting image.

8. Troubleshooting

Symptom Likely cause Fix
ChromeDriver session fails to start Chrome is missing, incompatible, or unavailable to the process; driver setup may also be incomplete. Confirm Chrome is installed and accessible. Check Selenium’s Chrome setup guidance and version compatibility.
Screenshot is desktop-shaped or breakpoints look wrong Only the window was resized, or mobile emulation was not applied before driver creation. Set the mobileEmulation option before constructing the driver; verify the configured metrics.
Image dimensions do not match CSS width DPR affects physical output pixels, and screenshot dimensions are not necessarily equal to CSS viewport dimensions. Record CSS viewport and DPR separately. Inspect the output image’s pixel dimensions rather than inferring them from width alone.
Screenshot is blank or missing product content The capture happened before the relevant content rendered, a page script failed, or navigation did not reach the intended state. Wait for a meaningful selector or state, inspect the current URL and page, and handle navigation timeouts deliberately.
Images are missing below the fold They may be lazy-loaded and not requested until near the viewport. Scroll through the content and wait for the images needed in the artifact, or use a capture workflow that prepares the full page.
Consent dialog or overlay covers the page The site presents a consent or promotional interface in this session. For an honest visual record, capture the displayed state. If your test requires the underlying page, interact with the site’s controls as a visitor would, then wait and capture that state.
save_screenshot returns false or no file appears Invalid path, missing parent directory, or unwritable destination. Create the directory first, use an absolute or known writable path, and check the method’s boolean result.
Navigation never settles Long-running network requests, page behavior, or a site-specific access response can delay readiness. Set a page-load timeout, catch the timeout when appropriate, inspect the page state, and wait for the exact content needed rather than requiring every background request to stop.

Automated access may be restricted by a site’s access rules. Check the applicable rules and avoid assuming a particular ecommerce site permits automation. A CAPTCHA or bot check is a site response; do not treat it as evidence that the page loaded normally.

9. Performance, reliability, and cost

Each Selenium capture starts or uses a browser session, loads the target page, waits for the selected state, and writes an image. Browser startup and the target page’s own loading work usually dominate a single local capture; no fixed duration is guaranteed. For repeated captures, reuse a driver for a controlled batch when session isolation is not required, and always close it in a finally block. For parallel work, account for the memory and CPU used by each browser session.

Reliability depends on keeping Chrome and ChromeDriver compatible, using explicit waits tied to content, setting timeouts, and recording the capture profile. Ecommerce pages can vary by session, location, inventory, personalization, consent state, and time; Selenium does not make those inputs constant. A screenshot is a record of the state the browser reached, not a guarantee that every page element or remote image loaded.

The Selenium workflow has no ScreenshotNeo per-shot charge, but it uses the compute, storage, and maintenance resources of the machine or browser environment where it runs. For a one-off or occasional local capture, that may be sufficient. If you need a managed screenshot API instead, ScreenshotNeo pricing is Free with 1,000 shots per month and no card; Starter is $5 for 3,000, Growth $15 for 15,000, Pro $39 for 60,000, Scale $99 for 250,000, and Business $249 for 1,000,000. Yearly billing gives two months free, and every feature is on every plan.

Or skip the browser setup

ScreenshotNeo is a website screenshot API and MCP server for developers. A GET request returns a screenshot or PDF. The following cURL, Python, and Node.js examples request an image of the same kind of target page; see the ScreenshotNeo API documentation for parameters and configuration.

curl -G "https://api.screenshotneo.com/v1/shot" \
  -d access_key=YOUR_API_KEY \
  --data-urlencode url=https://example.in/ \
  -o shot.webp
import requests

r = requests.get(
    "https://api.screenshotneo.com/v1/shot",
    params={"access_key": "YOUR_API_KEY", "url": "https://example.in/"},
    timeout=90,
)
r.raise_for_status()
open("shot.webp", "wb").write(r.content)
const q = new URLSearchParams({
  access_key: 'YOUR_API_KEY',
  url: 'https://example.in/'
});
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 removes cookie banners, newsletter popups, and chat widgets 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; paid plans start at $5 for 3,000. Sign up for 1,000 free screenshots a month.

FAQ

Does a mobile-width screenshot prove the page works on a real phone?

No. Chrome emulation is useful for repeatable responsive checks, but it is not a physical device. Test on real devices when hardware-specific behavior is part of the requirement.

The cited Selenium and Chrome sources do not establish an India-specific canonical viewport or device mix. Choose profiles based on your own audience data or testing scope.

Can I save the screenshot as JPEG instead of PNG?

Selenium’s documented standard screenshot methods save PNG. Convert the resulting image with an image-processing tool if another file format is needed.

Why can two captures of the same URL differ?

The page may depend on session state, location, personalization, inventory, time, or asynchronous content. Keep the browser profile and interactions consistent, and record relevant state alongside each capture.