Configure ChromeDriver Headless Mode with Selenium
In this article
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 any environment where a display is unavailable or unnecessary. By eliminating the overhead of rendering the browser window, headless mode typically consumes fewer system resources and can execute tasks slightly faster than headed mode.
What You'll Need
- Python installed: Ensure you have a stable version of Python (3.7+) installed on your machine.
- Selenium Library: The Selenium package must be installed via pip.
- Google Chrome Browser: A compatible version of the Chrome browser installed on the host machine.
- ChromeDriver: A driver executable that matches your Chrome browser version. Using a manager like
webdriver-manageris highly recommended to automate this. - IDE or Text Editor: A tool like VS Code, PyCharm, or a simple terminal to write and run your script.
Step-by-Step
- Install Necessary Dependencies: Start by installing the Selenium library and the WebDriver Manager. The manager eliminates the need to manually download and path the
chromedriver.exefile every time Chrome updates. Run the following command in your terminal:pip install selenium webdriver-manager. - Import Required Modules: In your Python script, you need to import the
webdrivermodule from Selenium and theChromeOptionsclass. If using the manager, importChromeDriverManagerfromwebdriver_manager.chromeand theServiceclass fromselenium.webdriver.chrome.service. - Initialize Chrome Options: Create an instance of
Options(). This object is used to customize the behavior of the Chrome browser. To enable headless mode, you must add the--headlessargument. In newer versions of Chrome (v109+), it is recommended to use--headless=newto ensure the browser uses the updated headless engine, which behaves more like the visible browser. - Configure Additional Stability Arguments: Headless browsers often encounter issues with window sizing or sandbox restrictions, especially on Linux servers. Add
--disable-gputo prevent crashes related to hardware acceleration and--no-sandboxto bypass OS-level security restrictions that often block headless execution in Docker containers. Additionally, add--disable-dev-shm-usageto prevent the browser from crashing due to limited shared memory in containerized environments. - Set a Window Size: Because there is no physical screen, Chrome may default to a very small resolution (e.g., 800x600), which can cause elements to hide behind hamburger menus or trigger mobile layouts. Use
options.add_argument("window-size=1920,1080")to simulate a standard desktop screen. - Instantiate the WebDriver: Combine the options and the service manager to launch the browser. Use
webdriver.Chrome(service=Service(ChromeDriverManager().install()), options=options). This line tells Selenium to download the correct driver version, apply your headless settings, and start the session. - Implement Your Automation Logic: You can now use standard Selenium commands such as
driver.get("url"),driver.find_element(), anddriver.click(). Since you cannot see the browser, usedriver.save_screenshot("debug.png")frequently during development to verify that the page is loading as expected. - Close the Session: Always end your script with
driver.quit(). This ensures that the headless Chrome process is fully terminated and does not remain as a zombie process consuming RAM on your server.
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, a manually downloaded driver will suddenly stop working, throwing a SessionNotCreatedException. This is why using webdriver-manager is critical for long-term stability.
Another common mistake is neglecting the User-Agent. Some websites can detect headless browsers because the default User-Agent string often contains the word "HeadlessChrome". This can lead to the site blocking your requests or serving a CAPTCHA. To avoid this, you should manually set a standard User-Agent string using 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").
Developers also often forget to handle implicit or explicit waits. In headless mode, page rendering can sometimes be faster or slower than in headed mode. Relying on time.sleep() is inefficient. Instead, use WebDriverWait to ensure elements are present before interacting with them, preventing NoSuchElementException errors that are harder to debug without a visual window.
Tips
For debugging headless scripts, utilize the "Headless-to-Headed" toggle. Create a boolean variable at the top of your script (e.g., HEADLESS = True) and wrap your options configuration in an if statement. This allows you to switch to visible mode instantly when a script fails, making it easier to see exactly where the automation is getting stuck.
To optimize performance, disable images and extensions. You can add experimental options to the options object to prevent Chrome from loading images, which significantly reduces bandwidth and speeds up page load times for data scraping tasks. Use options.add_experimental_option("prefs", {"profile.managed_default_content_settings.images": 2}).
If you are running scripts on a Linux server without any X11 display server installed, ensure you have the xvfb (X Virtual Frame Buffer) package installed if --headless=new still encounters issues. While the new headless mode is designed to be independent, some legacy dependencies in specific Linux distributions may still require a virtual display environment.
Troubleshooting
If your script crashes immediately upon startup, check the --no-sandbox and --disable-dev-shm-usage flags. These are almost always the culprit when running Selenium in Docker or on a restricted Linux VPS. Without these, Chrome may attempt to use a memory space that it doesn't have permission to access, resulting in a crash.
If you encounter a SessionNotCreatedException, it means your driver version is out of sync with your browser version. If you are not using webdriver-manager, you must visit the Chrome for Testing availability dashboard, download the version matching your browser's "About Chrome" page, and update your executable path. If you are using the manager, try clearing your .wdm cache folder to force a fresh download.
When a website refuses to load or returns a 403 Forbidden error only in headless mode, it is likely a bot detection mechanism. Try adding the --disable-blink-features=AutomationControlled argument. This removes the navigator.webdriver flag from the browser, making it harder for websites to identify the session as an automated script.
If elements are not being found despite being present in the headed version, check your window size. Headless mode does not have a physical screen to determine resolution. If you don't set window-size, the browser might render the page in a mobile view, causing desktop elements to be hidden or moved. Always explicitly set a resolution like 1920x1080.
Frequently Asked Questions
Is headless mode faster than headed mode?
Yes, generally it is faster because the system does not have to spend CPU and GPU resources rendering the actual pixels of the browser window on a screen.
Can I still take screenshots in headless mode?
Yes, the save_screenshot() method works perfectly in headless mode and is the primary way to debug what the browser is seeing.
Does headless mode work on Linux servers without a GUI?
Yes, that is its primary purpose. By using the --headless flag and --no-sandbox, you can run Chrome on a command-line-only server.
Why is the website blocking my headless browser?
Many sites check for the "HeadlessChrome" User-Agent or the navigator.webdriver property. Customizing the User-Agent and disabling automation features can help bypass this.
What is the difference between --headless and --headless=new?
The --headless=new flag uses the full Chrome browser engine without a window, whereas the old --headless used a separate, stripped-down implementation that sometimes behaved differently than the real browser.