Open In App

How to hide Firefox window (Selenium WebDriver)?

Last Updated : 21 Aug, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

In situations where you might wish to execute tests without a visible browser window, while automating web tests with Selenium WebDriver; it is possible for one to run headless browsers for example which will help save resources and speed up the execution of these tests. This article will cover how to run Firefox in headless mode using Selenium WebDriver.

Prerequisites: Ensure Python is installed on your system.

Step-by-step Implementation

Step 1. Install Selenium

For this tutorial, we will need to import a selenium package.

Run the following command in your command prompt to install selenium:

 pip install selenium

Step 2. Import Necessary Modules

After installing Selenium from Step 1, you need to import the required classes from the Selenium package:

Python
from selenium import webdriver
from selenium.webdriver.firefox.options import Options

Step 3. Configure Firefox Options

Next, configure Firefox to run in headless mode.

This can be done by setting the headless option to `True`:

Python
options = Options()
options.headless = True  # Enable headless mode

Step 4. Initiate web driver actions

In this step we will initiate the WebDriver with the configured headless option and perform any web actions as usual.

For example, let's open a webpage and print its title:

Python
driver = webdriver.Firefox(options=options) #Initiate web driver
driver.get("https://www.example.com")
print("Page title is:", driver.title)

Step 5. Close the Browser

Since, our actions are complete now, we have to close the browser:

Python
driver.quit()

Complete code:

For your reference here is the full code implementation:

Python
from selenium import webdriver
from selenium.webdriver.firefox.options import Options

# Set up Firefox options
options = Options()
options.headless = True  # Enable headless mode

# Initialize the WebDriver with headless option
driver = webdriver.Firefox(options=options)

# Open a webpage
driver.get("https://www.example.com")

# Perform some actions (for example, get the page title)
print("Page title is:", driver.title)

# Close the browser
driver.quit()

Output:

Running the script above will result in the following console output without displaying any Firefox window:

Screenshot-2024-08-09-150651
Console output

Conclusion

Using Selenium WebDriver to run Firefox in a headless manner is an efficient method for carrying out tests without the need for a visible browser window. This method is especially useful in non-GUI environments and can help make automated testing processes smoother.


Next Article
Article Tags :

Similar Reads