pythonseleniumfirefoxfirefox-headless

The right way to run Firefox in headless mode (Selenium, Python)


I was wondering how to run hidden Firefox window when testing a page in Selenium and came across this solution. It says that I can run Firefox in headless mode like this:

from selenium import webdriver
import os
os.environ['MOZ_HEADLESS'] = '1'
driver = webdriver.Firefox()
driver.get("https://www.google.com/")
driver.close()

But it earned no votes whatsoever. It seems like people think it is a wrong answer. Why?

Also, in official documentation I found that it can be done like this:

from selenium import webdriver
from selenium.webdriver.firefox.options import Options
options = Options()
options.add_argument('-headless')
driver = webdriver.Firefox(options=options)
driver.get("https://www.google.com/")
driver.close()

Can someone explain the difference between the two ways?


Solution

  • The first solutions sets an environment variable on your computer, i.e. changing your platform. According to the docs

    If the platform supports the putenv() function, this mapping may be used to modify the environment

    It will work only if your platform supports putenv()

    Availability: most flavors of Unix, Windows.

    The second solution sets the webdriver instance with some options, without changing your platform.