Software Development and QA Tips

Run Headless Browser (Python and Selenium) In a Unit Testing Framework

Written by Timothy Joseph | Jul 19, 2021 4:00:00 PM

Headless browsers are simulation programs that execute like any other browser, but without any UI. As a result, you are saved from the common challenges of running Selenium tests, which can include slow rendering on the browser and interference of other apps running on your machine.

SeleniumWebDriver 3 and SeleniumWebDdriver 4 offer various configurations to run popular browsers like Chrome, Firefox, and Edge in headless mode. As a result, you get the following benefits:

  • Optimize CI Pipeline - Can be used to execute automated tests remotely and release pipelines for continuous integration servers like GitLab.
  • Web Scraping - Used from creating a web scraper or data extractor that can visit websites and collect data.
  • Multi-browser Support - Supports the simulation of different browsers and their versions.
  • Faster Test Execution - Headless browsers do not take any time to load HTML, CSS, JavaScript, or images and instantly perform testing.

You can use the following code to run Firefox headless in the unit test framework (Python + Selenium):

from selenium import webdriver
from selenium.webdriver.firefox.options import Optionsoptions = Options()
options.headless = True
driver = webdriver.Firefox(options=options, executable_path=r'C:\Utility\BrowserDrivers\geckodriver.exe')
driver.get("http://google.com/")
print ("Headless Firefox Initialized")
driver.quit()