Selenium Chrome Screenshots in Docker: Full Setup Guide
In this article
Taking screenshots with Selenium and Chrome inside a Docker container allows you to automate visual regression testing and page captures in a consistent, isolated environment. This process involves running a headless Chrome browser within a Linux-based container, using a Selenium WebDriver to navigate to a URL, and saving the resulting image to a persistent volume so the file remains accessible after the container exits. To achieve this, you must configure the Chrome options to run without a graphical user interface (GUI) and ensure the Docker container has the necessary dependencies to render web pages correctly.
What You'll Need
- Docker Installed: Docker Engine and Docker Compose installed on your local machine or server.
- Python or Java: A programming language with a Selenium client library installed.
- Chrome WebDriver: A version of ChromeDriver that matches the version of Chrome installed in the container.
- A Dockerfile: A custom configuration to install Chrome and the driver, or a pre-built Selenium image.
- Write Permissions: A mapped volume or directory where the container can save the .png files.
Step-by-Step
- Create a Dockerfile for the Environment: While official Selenium images exist, creating your own ensures version parity. Start with a Python base image and install the Google Chrome stable binary. You must also install the corresponding ChromeDriver. Use
apt-getto installwgetandgnupgto handle the Chrome repository keys. Ensure you installfonts-liberationandfontconfig; otherwise, your screenshots will show empty squares instead of text because the container lacks system fonts. - Configure Headless Chrome Options: Since Docker containers typically do not have a display server (X11), you must run Chrome in
--headlessmode. In your Selenium code, initializeChromeOptions. Add the argument--headless=new(for newer Chrome versions) or--headless. Crucially, add--no-sandboxand--disable-dev-shm-usage. The--no-sandboxflag is required because Chrome's sandbox requires privileges that Docker containers often lack. The--disable-dev-shm-usageflag prevents the browser from crashing due to the small default size of/dev/shmin Docker. - Set the Window Size: Headless browsers often default to a very small resolution (e.g., 800x600). To get a useful screenshot, use
options.add_argument("--window-size=1920,1080"). This ensures the page renders in a desktop layout rather than a mobile layout, which would change the visual structure of the screenshot. - Implement the Screenshot Logic: Use the Selenium
save_screenshot("filename.png")method. In your script, navigate to the target URL usingdriver.get(url). It is highly recommended to implement an explicit wait (usingWebDriverWait) to ensure that elements have fully loaded before the capture occurs. If you capture the page immediately after thegetcall, you may end up with a screenshot of a loading spinner or a blank page. - Set Up Docker Volume Mapping: Files saved inside a container are ephemeral. To retrieve the screenshot, map a local folder to the container's output folder using the
-vflag in the Docker CLI or thevolumeskey in Docker Compose. For example,-v $(pwd)/screenshots:/app/screenshots. In your code, specify the path to save the image as/app/screenshots/page.png. - Build and Run the Container: Build your image using
docker build -t selenium-chrome-screenshots .and run it withdocker run --rm -v $(pwd)/screenshots:/app/screenshots selenium-chrome-screenshots. The--rmflag ensures the container is cleaned up after the script finishes, leaving only the screenshot file in your local directory.
Common Mistakes
One of the most frequent errors is forgetting the --no-sandbox argument. Without this, the Chrome process will fail to start immediately, often throwing a generic "SessionNotCreatedException" or a "DevToolsActivePort file doesn't exist" error. Another common pitfall is ignoring the shared memory limit. Docker's default shared memory size is 64MB, which is insufficient for modern web pages. This leads to random browser crashes during the rendering of heavy sites. Always use --disable-dev-shm-usage to force Chrome to use the disk instead of shared memory.
Developers also frequently forget to install fonts. A Linux container is a stripped-down environment. If you don't install a font package like ttf-dejavu or fonts-liberation, Chrome cannot render text. You will get a screenshot that looks perfectly laid out but contains no readable words, only blocks. Finally, avoid using driver.save_screenshot() without first setting a specific window size. If you don't, you'll get inconsistent screenshot dimensions depending on the default environment settings, making visual comparison tests impossible.
Tips
To capture a full-page screenshot (the entire scrollable height of the page) rather than just the visible viewport, you need to calculate the total height of the body. Use JavaScript via driver.execute_script("return document.body.scrollHeight") to find the height, then set the window size dynamically using driver.set_window_size(1920, height) before taking the screenshot. This is essential for long landing pages.
For better performance, consider using the selenium/standalone-chrome image. This image is maintained by the Selenium project and comes pre-configured with Chrome and ChromeDriver. Instead of putting your script inside the container, you can run the container as a remote server and connect to it from your local machine using webdriver.Remote(). This separates the execution logic from the browser environment, making it easier to update your code without rebuilding the Docker image every time.
If you are running tests in a CI/CD pipeline, use a docker-compose.yml file to orchestrate the browser and the test runner. This allows you to define a network where the test runner can reach the Chrome container via a hostname (e.g., http://chrome:4444/wd/hub), simplifying the connection strings in your configuration files.
Troubleshooting
If you encounter a "WebDriverException: Message: unknown error: cannot find Chrome binary," it means the path to the Chrome executable is not in the system PATH of the container. Check your Dockerfile to ensure Chrome was installed in a standard location like /usr/bin/google-chrome. You can explicitly set the binary location in your code using options.binary_location = "/usr/bin/google-chrome".
When screenshots appear blank or white, it is often a timing issue. The page may have loaded the HTML, but the CSS or JavaScript rendering the content hasn't finished. Increase your wait times or use WebDriverWait to wait for a specific element to be visible. If the issue persists, check if the site has bot detection. Some sites block headless Chrome. In such cases, try adding a realistic User-Agent string via options.add_argument("user-agent=Mozilla/5.0...") to make the request look like it is coming from a standard browser.
If the container crashes with an "Out of Memory" error, increase the memory limit allocated to Docker in your system settings. Chrome is memory-intensive, especially when rendering complex modern web applications. If you are using Docker Compose, you can specify mem_limit: 2g to ensure the browser has enough headroom to operate without being killed by the OOM (Out of Memory) killer.
Frequently Asked Questions
Why are my screenshots showing empty boxes instead of text?
This happens because the Docker container lacks the necessary system fonts to render characters. Install fonts-liberation or ttf-dejavu in your Dockerfile to fix this.
Can I take screenshots of a specific element instead of the whole page?
Yes. Instead of calling driver.save_screenshot(), find the specific element using driver.find_element() and then call element.screenshot("element.png").
Do I need to install ChromeDriver manually in the container?
Yes, if you are building a custom image. The version of ChromeDriver must exactly match the version of Chrome installed. Using the official selenium/standalone-chrome image avoids this manual setup.
How do I handle pop-ups or cookie banners in screenshots?
You must write code to find the "Accept" button of the cookie banner and click it using element.click() before triggering the screenshot method.
Is there a way to take screenshots without using a volume?
You can upload the screenshot to a cloud storage bucket (like AWS S3) directly from the script, or use a base64 encoding to send the image data back to the calling application via an API response.