Run Chrome, Edge, and Firefox Headless with Selenium Python
In this article
Running browsers in headless mode with Selenium and Python allows you to automate web interactions without a graphical user interface (GUI) appearing on your screen. This is essential for running scrapers or automated tests on servers, CI/CD pipelines (like GitHub Actions or Jenkins), or simply to save system resources on your local machine. In headless mode, the browser engine renders the page in memory, allowing the script to interact with elements, click buttons, and extract data exactly as a visible browser would, but without the overhead of rendering a window.
What You'll Need
- Python 3.x: Ensure Python is installed and added to your system PATH.
- Selenium Library: The core framework for browser automation.
- Web Browsers: Google Chrome, Microsoft Edge, and Mozilla Firefox installed on the machine.
- WebDriver Manager: While you can manually download drivers, the
webdriver-managerlibrary is highly recommended to automatically handle version matching between the browser and the driver. - A Code Editor: VS Code, PyCharm, or any text editor of your choice.
Step-by-Step
- Install Required Packages: Open your terminal or command prompt and install Selenium and the WebDriver Manager. This ensures you don't have to manually update
chromedriver.exeorgeckodriver.exeevery time your browser updates. Run the following command:pip install selenium webdriver-manager - Configure Headless Chrome: Chrome requires the
ChromeOptionsclass to enable headless mode. You must instantiate the options object, add the--headlessargument, and then pass those options into the WebDriver constructor. For modern versions of Chrome,--headless=newis recommended as it provides a more accurate representation of the full browser.
Example code snippet:from selenium import webdriver from selenium.webdriver.chrome.service import Service from selenium.webdriver.chrome.options import Options from webdriver_manager.chrome import ChromeDriverManager chrome_options = Options() chrome_options.add_argument("--headless=new") chrome_options.add_argument("--disable-gpu") chrome_options.add_argument("--window-size=1920,1080") driver = webdriver.Chrome(service=Service(ChromeDriverManager().install()), options=chrome_options) - Configure Headless Edge: Since Microsoft Edge is built on the Chromium engine, the process is nearly identical to Chrome. You will use
EdgeOptionsand the--headlessargument. Ensure you use the Edge-specific WebDriver Manager to fetch the correct binary.
Example code snippet:from selenium import webdriver from selenium.webdriver.edge.service import Service from selenium.webdriver.edge.options import Options from webdriver_manager.microsoft import EdgeChromiumDriverManager edge_options = Options() edge_options.add_argument("--headless") edge_options.add_argument("--disable-gpu") driver = webdriver.Edge(service=Service(EdgeChromiumDriverManager().install()), options=edge_options) - Configure Headless Firefox: Firefox uses a different engine (Gecko), so it utilizes
FirefoxOptions. Unlike Chromium browsers, Firefox has a dedicated method calledadd_argument("-headless")or a specific property to set the headless state.
Example code snippet:from selenium import webdriver from selenium.webdriver.firefox.service import Service from selenium.webdriver.firefox.options import Options from webdriver_manager.firefox import GeckoDriverManager firefox_options = Options() firefox_options.add_argument("-headless") driver = webdriver.Firefox(service=Service(GeckoDriverManager().install()), options=firefox_options) - Implement Page Navigation and Interaction: Once the driver is initialized in headless mode, you use standard Selenium commands to navigate to a URL and interact with the page. Because there is no visual window, you cannot see if a page fails to load or if a pop-up blocks your script. It is best practice to use
driver.get("url")and then useWebDriverWaitto ensure elements are present before interacting with them. - Capture State for Debugging: Since you cannot see the browser, you should implement screenshotting. This allows you to save a PNG of the page at a specific moment to verify that the headless browser is seeing what you expect it to see. Use
driver.save_screenshot("debug.png"). - Close the Session: Always call
driver.quit()at the end of your script. In headless mode, if you only usedriver.close()or let the script crash, you may leave "zombie" browser processes running in the background, which will eventually consume all your system RAM.
Common Mistakes
One of the most frequent errors is neglecting to set a window size. In headless mode, browsers often default to a very small resolution (e.g., 800x600). If the website you are automating uses a responsive design, the browser may render the mobile version of the site instead of the desktop version. This causes elements to disappear or move into "hamburger" menus, leading to NoSuchElementException errors. Always explicitly set the window size using --window-size=1920,1080 in your options.
Another common mistake is forgetting to handle User-Agents. Some websites can detect that a browser is running in headless mode because the User-Agent string often contains the word "HeadlessChrome". This can lead to the site blocking your requests or serving you a CAPTCHA. To avoid this, you can manually set a real browser User-Agent string in the options: 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").
Users also frequently confuse driver.close() with driver.quit(). While close() shuts the current window, quit() destroys the entire driver session and closes all associated windows and processes. In a headless environment, failing to use quit() often leads to a buildup of background processes that can slow down or crash a server.
Tips
To increase the reliability of headless scripts, implement Explicit Waits. Because headless browsers can sometimes render pages faster or slower than headed ones, using time.sleep() is inefficient and unreliable. Instead, use selenium.webdriver.support.ui.WebDriverWait combined with expected_conditions. This tells Selenium to wait for a specific element to become clickable or visible before proceeding, which prevents scripts from crashing during slow network responses.
If you are running these browsers on a Linux server without any X11 display server installed, you may need to add the --no-sandbox and --disable-dev-shm-usage arguments. The --no-sandbox flag is often required in Docker containers to bypass the OS security model that prevents the browser from starting. The --disable-dev-shm-usage flag forces the browser to use the disk instead of /dev/shm (shared memory), which prevents crashes in environments with limited shared memory allocations.
For those needing to scrape data from JavaScript-heavy sites, consider using the --disable-gpu flag. While modern versions of Chrome have improved this, disabling hardware acceleration can reduce memory consumption and prevent certain rendering glitches in headless environments where no actual GPU is available.
Troubleshooting
If your script fails to launch the browser, the first step is to check the version compatibility. Even with webdriver-manager, occasionally a browser update rolls out before the manager can sync. Try updating your manager with pip install --upgrade webdriver-manager. If the error persists, try running the browser in non-headless mode first. If the script works with the GUI but fails in headless mode, the issue is likely related to the User-Agent or the window size, as the website is detecting the headless state or the elements are hidden due to a small viewport.
If you encounter a SessionNotCreatedException, it usually means the driver version does not match the browser version. Ensure that no old versions of the driver are manually placed in your system PATH, as Selenium might be picking up an outdated chromedriver.exe from a folder instead of the one provided by the manager.
When elements are not being found in headless mode but are visible in headed mode, use the driver.page_source command to print the HTML to a file. Compare the headless HTML with the headed HTML. Often, you will find that the headless browser is being served a "bot detection" page or a different layout entirely. If this happens, adding a custom User-Agent and disabling the "automation controlled" flag via chrome_options.add_experimental_option("excludeSwitches", ["enable-automation"]) can help.
Frequently Asked Questions
Is headless mode faster than headed mode?
Yes, generally. Because the system does not have to render the visual interface and paint the pixels on a screen, headless mode consumes less CPU and RAM, leading to faster execution times for most automation tasks.
Can I still take screenshots in headless mode?
Yes. The save_screenshot() method works perfectly in headless mode. It captures the state of the DOM as rendered in memory and saves it as an image file, which is the primary way to debug headless scripts.
Do I still need a WebDriver for headless mode?
Yes. Headless mode is simply a configuration of the browser; it still requires the WebDriver (like ChromeDriver or GeckoDriver) to act as the bridge between your Python code and the browser engine.
Will websites know I am using a headless browser?
By default, yes. Many websites check for the "headless" string in the User-Agent or look for specific JavaScript flags (like navigator.webdriver). You can mitigate this by spoofing the User-Agent and using specific Chrome options to hide the automation flag.
Can I run headless browsers in a Docker container?
Yes, but you must install the browser binaries within the Docker image and use the --no-sandbox and --disable-dev-shm-usage arguments to ensure the browser can start without a display server or excessive shared memory.