How to run headless Firefox with Selenium in Python?
Asked Answered
S

8

192

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")
Systematize answered 15/10, 2017 at 8:58 Comment(1)
I just wanted to add that your Firefox version should be 56+ for this to work. Took me a while to figure out why any of the solution posted did not work on mine. developer.mozilla.org/en-US/Firefox/Headless_modeBehindhand
O
348

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?

Outgoings answered 16/10, 2017 at 10:32 Comment(5)
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 summaryFarland
MOZ_HEADLESS=1 python manage.py test did the trick! No need for xvfb-run anymore (:Mephitis
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.Puffery
is that same from java code perspectives?Martynne
Hello @undetected-selenium Could you give me some tip for this question, please? #75859006Mayapple
F
80

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")
Freed answered 24/4, 2019 at 15:54 Comment(5)
Python 3.8.2 / selenium.__version__ == '3.141.0' works great!Bergstrom
add from selenium import webdriver to invoke webdriver.Firefox()Flowerlike
The accepted answer still works with the latest version of Firefox and geckodriverMillihenry
@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.Zombie
THis is also the way to go for me on Ubuntu 20.04 and Python 3.8.10Pennyweight
S
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

Sympathy answered 29/12, 2018 at 7:41 Comment(2)
options.headless also has been deprecated will need options.add_argument("-headless") selenium.dev/blog/2023/headless-is-going-awayCorporator
Despite that site stating Chrome, that change is also needed for Firefox.Entirely
S
7

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
Shows answered 3/9, 2023 at 14:23 Comment(0)
D
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')
Despinadespise answered 29/7, 2020 at 9:27 Comment(0)
I
4

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)
Ian answered 19/9, 2020 at 20:49 Comment(0)
C
4
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

Calorimeter answered 27/12, 2020 at 7:5 Comment(0)
B
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()
Blackmarketeer answered 14/10, 2022 at 9:26 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.