187

I am running this code with python, selenium, and firefox but still get 'head' version of firefox:

binary = FirefoxBinary('C:\\Program Files (x86)\\Mozilla Firefox\\firefox.exe', log_file=sys.stdout)
binary.add_command_line_options('-headless')
self.driver = webdriver.Firefox(firefox_binary=binary)

I also tried some variations of binary:

binary = FirefoxBinary('C:\\Program Files\\Nightly\\firefox.exe', log_file=sys.stdout)
        binary.add_command_line_options("--headless")
1

8 Answers 8

343

To invoke Firefox Browser headlessly, you can set the headless property through Options() class as follows:

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

options = 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()

There's another way to accomplish headless mode. If you need to disable or enable the headless mode in Firefox, without changing the code, you can set the environment variable MOZ_HEADLESS to whatever if you want Firefox to run headless, or don't set it at all.

This is very useful when you are using for example continuous integration and you want to run the functional tests in the server but still be able to run the tests in normal mode in your PC.

$ MOZ_HEADLESS=1 python manage.py test # testing example in Django with headless Firefox

or

$ export MOZ_HEADLESS=1   # this way you only have to set it once
$ python manage.py test functional/tests/directory
$ unset MOZ_HEADLESS      # if you want to disable headless mode

Steps through YouTube Video


Outro

How to configure ChromeDriver to initiate Chrome browser in Headless mode through Selenium?

5
  • 4
    Upgraded Selenium (3.14.1) and PhantomJS is now deprecated, so none of my tests worked. Had to switch to Firefox --headless in a hurry. Thanks for this excellent summary
    – MortenB
    Oct 16, 2018 at 15:34
  • 8
    MOZ_HEADLESS=1 python manage.py test did the trick! No need for xvfb-run anymore (: Jan 24, 2019 at 21:49
  • 3
    I'd suggest removing at least the first link to YouTube, it's a 15 minutes video to just say options.addArguments("--headless");. People don't need to go through YouTube ads to see that.
    – quiram
    Mar 22, 2022 at 16:13
  • is that same from java code perspectives?
    – gumuruh
    May 27, 2022 at 10:02
  • Hello @undetected-selenium Could you give me some tip for this question, please? stackoverflow.com/questions/75858506/… Mar 27 at 17:38
69

The first answer does't work anymore.

This worked for me:

from selenium.webdriver.firefox.options import Options as FirefoxOptions
from selenium import webdriver

options = FirefoxOptions()
options.add_argument("--headless")
driver = webdriver.Firefox(options=options)
driver.get("http://google.com")
5
  • 1
    Python 3.8.2 / selenium.__version__ == '3.141.0' works great!
    – hirnwunde
    Apr 21, 2020 at 17:58
  • 1
    add from selenium import webdriver to invoke webdriver.Firefox()
    – Snow
    Apr 24, 2020 at 10:09
  • 3
    The accepted answer still works with the latest version of Firefox and geckodriver Apr 24, 2020 at 15:10
  • @PedroLobito : options.headless = True works but throws a deprecation warning: DeprecationWarning: headless property is deprecated, instead use add_argument('-headless') It's good to avoid these in the long term because they mean it'll stop working eventually.
    – edison23
    Feb 3 at 10:20
  • 1
    THis is also the way to go for me on Ubuntu 20.04 and Python 3.8.10
    – Simao
    Oct 25 at 19:36
14

My answer:

set_headless(headless=True) is deprecated. 

https://seleniumhq.github.io/selenium/docs/api/py/webdriver_firefox/selenium.webdriver.firefox.options.html

options.headless = True

works for me

1
4
Used below code to set driver type based on need of Headless / Head for both Firefox and chrome:

// Can pass browser type 

if brower.lower() == 'chrome':
    driver = webdriver.Chrome('..\drivers\chromedriver')
elif brower.lower() == 'headless chrome':
    ch_Options = Options()
    ch_Options.add_argument('--headless')
    ch_Options.add_argument("--disable-gpu")
    driver = webdriver.Chrome('..\drivers\chromedriver',options=ch_Options)
elif brower.lower() == 'firefox':
    driver = webdriver.Firefox(executable_path=r'..\drivers\geckodriver.exe')
elif brower.lower() == 'headless firefox':
    ff_option = FFOption()
    ff_option.add_argument('--headless')
    ff_option.add_argument("--disable-gpu")
    driver = webdriver.Firefox(executable_path=r'..\drivers\geckodriver.exe', options=ff_option)
elif brower.lower() == 'ie':
    driver = webdriver.Ie('..\drivers\IEDriverServer')
else:
    raise Exception('Invalid Browser Type')
3

To the OP or anyone currently interested, here's the section of code that's worked for me with firefox currently:

opt = webdriver.FirefoxOptions()
opt.add_argument('-headless')
ffox_driver = webdriver.Firefox(executable_path='\path\to\geckodriver', options=opt)
3
from selenium.webdriver.firefox.options import Options

if __name__ == "__main__":
    options = Options()
    options.add_argument('-headless')
    driver = Firefox(executable_path='geckodriver', firefox_options=options) 
    wait = WebDriverWait(driver, timeout=10)
    driver.get('http://www.google.com')

Tested, works as expected and this is from Official - Headless Mode | Mozilla

0
2

Nowadays with this code:

options                 = Options()
options.headless        = True
driver                  = webdriver.Firefox(executable_path=GeckoDriverManager().install(),options=options)

We have a warning:

DeprecationWarning: executable_path has been deprecated, please pass in a Service object

Changing to this one, works perfectly:

#!/usr/bin/env python
# -*- coding: utf-8 -*-

# selenium drivers: https://www.selenium.dev/documentation/webdriver/getting_started/install_drivers/
# pip3 install selenium
# pip3 install webdriver-manager
# for custom firefox installation: link firefox to /usr/bin/firefox, example: ln -s /opt/firefox/firefox-bin /usr/bin/firefox

from selenium                           import webdriver
from webdriver_manager.firefox          import GeckoDriverManager
from selenium.webdriver.firefox.options import Options
from selenium.webdriver.firefox.service import Service

options                 = Options()
options.headless        = True
service                 = Service(executable_path=GeckoDriverManager().install())
driver                  = webdriver.Firefox(service=service, options=options)

driver.get("http://google.com/")
print("Headless Firefox Initialized")
driver.quit()
1

You can run headless Firefox with Selenium in Python as shown below:

from selenium import webdriver

options = webdriver.FirefoxOptions()
options.add_argument("-headless") # Here
driver = webdriver.Firefox(options=options)

Or:

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

options = Options()
options.add_argument("-headless") # Here
driver = webdriver.Firefox(options=options)

In addition, the examples below can test Django Admin with headless Firefox, Selenium, pytest-django and Django. *My answer explains how to test Django Admin with multiple headless browsers(Chrome, Microsoft Edge and Firefox), Selenium, pytest-django and Django:

# "tests/test_1.py"

import pytest
from selenium import webdriver
from django.test import LiveServerTestCase

@pytest.fixture(scope="class")
def firefox_driver_init(request):
    options = webdriver.FirefoxOptions()
    options.add_argument("-headless")
    firefox_driver = webdriver.Firefox(options=options)
    request.cls.driver = firefox_driver
    yield
    firefox_driver.close()

@pytest.mark.usefixtures("firefox_driver_init")
class Test_URL_Firefox(LiveServerTestCase):
    def test_open_url(self):
        self.driver.get(("%s%s" % (self.live_server_url, "/admin/")))
        assert "Log in | Django site admin" in self.driver.title

Or:

# "tests/conftest.py"

import pytest
from selenium import webdriver

@pytest.fixture(scope="class")
def firefox_driver_init(request):
    options = webdriver.FirefoxOptions()
    options.add_argument("-headless")
    firefox_driver = webdriver.Firefox(options=options)
    request.cls.driver = firefox_driver
    yield
    firefox_driver.close()
# "tests/test_1.py"

import pytest
from django.test import LiveServerTestCase

@pytest.mark.usefixtures("firefox_driver_init")
class Test_URL_Firefox(LiveServerTestCase):
    def test_open_url(self):
        self.driver.get(("%s%s" % (self.live_server_url, "/admin/")))
        assert "Log in | Django site admin" in self.driver.title

Not the answer you're looking for? Browse other questions tagged or ask your own question.