User Agents

Web browsers and everyday web tech, explained

Configure ChromeDriver Headless Mode with Selenium

· 6 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

Configuring ChromeDriver to run in headless mode allows you to execute browser automation tasks without a visible graphical user interface (GUI). This is essential for running scripts on servers, CI/CD pipelines, or background tasks where a display is unavailable or unnecessary. By utilizing the ChromeOptions class in Selenium, you can instruct the browser to run in the background, which typically reduces memory overhead and increases execution speed by skipping the rendering of the visual window.

What You'll Need

  • Python installed: Ensure you have a stable version of Python (3.7+) installed on your system.
  • Selenium Library: The Selenium package must be installed via pip (pip install selenium).
  • Google Chrome Browser: The actual browser must be installed on the machine where the script will run.
  • ChromeDriver: A driver executable that matches the version of your installed Chrome browser.
  • Webdriver Manager (Optional but Recommended): A library to automate the downloading and updating of the driver (pip install webdriver-manager).

Step-by-Step

  1. Import Necessary Modules: Start your Python script by importing the Selenium webdriver and the ChromeOptions class. If you are using the webdriver-manager, import the ChromeDriverManager as well. This ensures you have access to the configuration tools required to modify the browser's startup behavior.
  2. Initialize ChromeOptions: Create an instance of the Options class. This object acts as a container for all the arguments and preferences you want to pass to the Chrome binary upon launch. Without this object, Selenium will launch Chrome with default settings, which always includes a visible window.
  3. Add the Headless Argument: Use the add_argument() method to specify headless mode. For modern versions of Chrome (version 109 and later), the recommended argument is "--headless=new". The "new" flag ensures that the browser uses the updated headless engine, which behaves more like the headed version, providing better support for extensions and more accurate rendering of page elements.
  4. Configure Window Size: Because there is no physical screen to determine the viewport, headless browsers often default to a very small window size (e.g., 800x600). This can cause elements to hide behind hamburger menus or trigger mobile-responsive layouts that break your selectors. Use options.add_argument("--window-size=1920,1080") to simulate a standard desktop resolution.
  5. Disable GPU Acceleration: In many server environments (especially Linux), the browser may attempt to use hardware acceleration for rendering, which can lead to crashes or errors if no GPU is present. Add the argument "--disable-gpu" to ensure stability across different hardware configurations.
  6. Handle Sandbox Restrictions: If you are running your script inside a Docker container or as a root user on Linux, Chrome's security sandbox may prevent the browser from starting. To bypass this, add the "--no-sandbox" argument. This is a common requirement for cloud-based automation.
  7. Instantiate the WebDriver: Pass your configured options object into the webdriver.Chrome() constructor. If using webdriver-manager, the syntax would be webdriver.Chrome(service=Service(ChromeDriverManager().install()), options=options). This tells Selenium to launch the browser using the specific headless parameters you defined.
  8. Verify Execution: Write a simple test case, such as navigating to a website and printing the page title or taking a screenshot. Since you cannot see the browser, using driver.save_screenshot("test.png") is the best way to confirm that the page is rendering correctly in the background.

Common Mistakes

One of the most frequent errors is failing to match the Chrome browser version with the ChromeDriver version. If Chrome updates automatically in the background, your existing driver may become obsolete, resulting in a SessionNotCreatedException. Using a manager tool solves this, but manual users must check versions frequently.

Another common mistake is forgetting to set a window size. Developers often find that their scripts work perfectly in headed mode but fail in headless mode because the default headless viewport is too small. This causes elements to become "not interactable" because they are hidden or shifted by the browser's responsive design logic.

Many users also forget to include the --disable-dev-shm-usage argument when running in Docker. Linux systems often allocate a small amount of shared memory (/dev/shm) to containers. Chrome uses this space for its rendering process, and if it runs out, the browser will crash unexpectedly. Adding this flag forces Chrome to use the disk instead of shared memory.

Tips

To make your headless browser less detectable by websites that block bots, you should set a realistic User-Agent string. Headless Chrome often identifies itself as "HeadlessChrome" in the request headers, which is a red flag for many security filters. Use options.add_argument("user-agent=Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36") to blend in with standard traffic.

For debugging headless scripts, utilize the driver.get_screenshot_as_file() method. Since you cannot see the browser, capturing images of the page at critical failure points is the only way to understand why a click failed or why an element wasn't found. You can also log the HTML source of the page using driver.page_source to see if the content was actually loaded.

If you are performing heavy scraping, consider disabling images to save bandwidth and speed up page loads. This can be done by adding an experimental option to the ChromeOptions object that modifies the browser's preferences to block image loading.

Troubleshooting

If the browser fails to start and throws a "DevToolsActivePort file doesn't exist" error, it is usually a sign of a permission issue or a memory constraint. Ensure you have added both --headless=new and --no-sandbox. If you are on a Linux server, check if you have installed the necessary dependencies for Chrome, such as libnss3, libatk1.0-0, and libxcomposite1.

When elements are not found (NoSuchElementException) only in headless mode, the first step is to check the viewport size. If the size is correct, check if the site is detecting the headless flag. Some sites serve different content or a CAPTCHA when they detect a headless browser. In this case, updating the User-Agent or using a library like selenium-stealth can help bypass these checks.

If the script hangs indefinitely, it may be due to a page that never finishes loading (e.g., a page with a hanging socket or a large advertisement). Set a page load timeout using driver.set_page_load_timeout(30). This ensures that your script will throw a timeout exception rather than waiting forever, allowing you to handle the error gracefully.

Frequently Asked Questions

Is headless mode faster than headed mode?

Yes, headless mode is generally faster and consumes fewer system resources because the computer does not need to spend CPU and GPU cycles rendering the visual interface and managing the windowing system.

Can I still take screenshots in headless mode?

Yes, Selenium's screenshot methods work perfectly in headless mode. The browser still renders the page internally; it just doesn't display it on a screen, so you can still capture the visual state of the DOM.

Does headless mode support JavaScript?

Yes, headless Chrome is a full browser engine. It executes JavaScript, handles AJAX requests, and manages cookies exactly as the visible version of Chrome does.

What is the difference between --headless and --headless=new?

The original --headless flag used a separate, simplified browser implementation. The --headless=new flag (introduced in newer versions) uses the actual Chrome browser engine without a window, making it more compatible with modern web features and extensions.

Can I use Chrome extensions in headless mode?

Historically, extensions did not work in headless mode. However, with the --headless=new flag, Chrome now supports the loading and execution of extensions even when the GUI is disabled.