Run Selenium Headless in Firefox and Chrome using Python

Selenium is one of the most powerful tools for web automation testing. Python can run this tool using the Selenium module, which can be installed from the PyPI.

By default, Python selenium performs automation tests by opening the browser GUI, but it can also be run in the background without opening the GUI. In the second case, we say selenium is running in headless mode.

This guide shows how to run selenium in headless mode for Chromium-based (tested on Google Chrome and Chromium) and Firefox browsers. Before we do that, however, let’s cover some prerequisites (essential).

Prerequisites

Before using the code in this article, ensure that:

#1. Ensure you are running Python 3.

#2. [IMPORTANT] Ensure you are using the latest version of selenium

You can use pip to install or upgrade selenium by running the following line

pip install -U selenium

If you want to install a specific version of Selenium, use the following command (I am running Selenium 4.8.3 in this article).

pip install selenium==4.8.3

Running Selenium in Headless Mode in Firefox

Step 1: Import the required classes and functions

First, you need to import Firefox webdriver from Selenium. This function contains the classes of different browsers. Second, import the Options() from selenium.webdriver.firefox.options.

Step 2: Create options with headless property

To run Firefox in the background without the GUI, we need to set the headless property through the Options() class as follows:

Step 3: Invoke Firefox in headless mode

This can now be done by passing the options attribute in the Firefox Webdriver.

Let’s put it all together

Output:
Example Domain This domain is for use in illustrative examples in documents. You may use this domain in literature without prior coordination or asking for permission. More information…

Running Selenium in Headless mode in Chrome

You can invoke Chrome in the background using the Selenium package by slightly modifying what we did above. Here are the most important lines.

Then you can access a given site with the following code.

Conclusion

This guide discussed running Python selenium in headless mode in Firefox and Chrome browsers. When using the code in this article, ensure that you install the latest version of Selenium (the code in this post is based on Selenium v4.8.3).