User Agents

Web browsers and everyday web tech, explained

Crop Selenium Screenshot to Browser Viewport

· 4 min read · Browsers

In this article
  1. What You'll Need
  2. Step-by-Step
  3. Common Mistakes
  4. Tips
  5. Troubleshooting
  6. Frequently Asked Questions

When you take a screenshot with Selenium, the default behavior captures the full page, including content below the fold. Cropping it to the browser viewport gives you a clean image of exactly what the user sees, which is useful for visual regression testing, documentation, or bug reports. This guide shows you how to crop a Selenium screenshot to the viewport using Python and Pillow (PIL), with alternatives for Java and JavaScript.

What You'll Need

  • A Selenium WebDriver setup (Python, Java, or JavaScript) with a browser driver installed (e.g., ChromeDriver, GeckoDriver).
  • The Pillow library for Python (pip install Pillow), or equivalent image processing libraries for other languages (e.g., Java's BufferedImage, Node's sharp).
  • Basic knowledge of your Selenium WebDriver's API for taking screenshots.

Step-by-Step

  1. Take a full-page screenshot. Use Selenium's built-in screenshot method. In Python: driver.save_screenshot('full.png'). In Java: File src = ((TakesScreenshot)driver).getScreenshotAs(OutputType.FILE);. In JavaScript: await driver.takeScreenshot() and save the base64 string.
  2. Get the viewport dimensions. Use JavaScript to retrieve the viewport width and height. In Python: width = driver.execute_script('return window.innerWidth;') and height = driver.execute_script('return window.innerHeight;'). In Java: Long width = (Long) ((JavascriptExecutor)driver).executeScript("return window.innerWidth;");. In JavaScript: const width = await driver.executeScript('return window.innerWidth;');.
  3. Load the screenshot into an image object. In Python with Pillow: from PIL import Image; img = Image.open('full.png'). In Java: BufferedImage image = ImageIO.read(src);. In JavaScript with sharp: const sharp = require('sharp'); let image = sharp(Buffer.from(base64String, 'base64'));.
  4. Crop the image to the viewport. The crop box starts at (0,0) and ends at (width, height). In Python: cropped = img.crop((0, 0, width, height)). In Java: BufferedImage cropped = image.getSubimage(0, 0, width.intValue(), height.intValue());. In JavaScript: const croppedBuffer = await image.extract({ left: 0, top: 0, width: width, height: height }).toBuffer();.
  5. Save the cropped image. In Python: cropped.save('viewport.png'). In Java: ImageIO.write(cropped, "png", new File("viewport.png"));. In JavaScript: require('fs').writeFileSync('viewport.png', croppedBuffer);.
  6. Clean up. Optionally delete the temporary full-page screenshot if you no longer need it.

Common Mistakes

  • Using the wrong dimensions. Some people use window.outerWidth or window.outerHeight, which include browser chrome (toolbars, scrollbars). Always use window.innerWidth and window.innerHeight to get the viewport size.
  • Forgetting to account for scrollbars. The viewport size includes the scrollbar if present. If you want to exclude the scrollbar area, you can subtract its width, but most use cases want the full viewport as seen.
  • Cropping with integer values. JavaScript returns numbers as floats; if you pass them directly to a crop function that expects integers, you may get a TypeError. Cast to int (e.g., int(width) in Python).
  • Not waiting for the page to load. If you take the screenshot before the page is fully rendered, the viewport size may be incorrect. Use explicit waits for the page to be ready.

Tips

  • Use a helper function. Wrap the logic in a function that takes the driver and a file path, so you can reuse it across tests.
  • Handle responsive designs. If your page changes layout at different viewport sizes, set the window size explicitly before taking the screenshot to ensure consistency.
  • Consider device pixel ratio. For high-DPI screens, the screenshot may be larger than the CSS viewport. Multiply the viewport dimensions by window.devicePixelRatio if you need the physical pixel crop.
  • Use a temporary file for the full screenshot. Save it to a temp location and delete after cropping to avoid clutter.

Troubleshooting

  • Cropped image is blank or black. This usually means the viewport dimensions are zero. Check that the page is fully loaded and that you're using innerWidth/innerHeight correctly. Also, ensure the driver is not in a headless mode that returns 0 for these properties (some older versions had this issue).
  • Crop area exceeds image size. If the full-page screenshot is smaller than the viewport (e.g., because the page is shorter than the viewport), the crop will fail. In that case, set the crop height to min(height, img.height) and width similarly.
  • Image is cropped incorrectly on mobile emulation. Mobile emulation may have a different device pixel ratio. Use the ratio to adjust the crop dimensions as mentioned in Tips.
  • Java getSubimage throws RasterFormatException. This happens when the crop box exceeds the image bounds. Check the image dimensions and clamp the crop coordinates.

Frequently Asked Questions

Can I crop without taking a full-page screenshot first?

No, Selenium's screenshot method captures the entire page. You must crop afterward. Some third-party libraries offer viewport-only screenshots, but the standard API does not.

Does this work in headless mode?

Yes, headless browsers still have a viewport. However, some older headless modes had issues with innerHeight returning 0; using a newer version or setting an explicit window size usually fixes it.

Why is my cropped image larger than the viewport?

This can happen on high-DPI displays where the screenshot is taken at device pixel ratio. Multiply your crop dimensions by window.devicePixelRatio to get the correct pixel size.

Can I crop to a specific element instead of the whole viewport?

Yes, get the element's bounding rect using element.getBoundingClientRect() and use those coordinates for the crop box. The same cropping logic applies.

Is there a way to do this without Pillow in Python?

You can use other image libraries like OpenCV or the built-in tkinter (though not recommended). Pillow is the standard and easiest for this task.

Does this work with Selenium Grid or remote WebDriver?

Yes, the screenshot and JavaScript execution work the same way over the wire. Just ensure the remote browser has a viewport set.