Configuring Selenium for Headless Firefox in Python

How can I configure Selenium to run headless Firefox in Python?

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")

With a fair share of experience working with Selenium, here’s a robust way to configure it for headless Firefox in Python:


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

Building upon the first response here, I’ve noticed that things evolve quickly in the tech world. For a more up-to-date solution, try this:


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")

Adding to the wealth of options, let me provide you with a couple of alternatives, depending on your preference. First, using the Options class:


from selenium import webdriver

from selenium.webdriver.firefox.options import Options

options = Options()

options.headless = True

driver = webdriver.Firefox(options=options)

driver.get('https://www.example.com')

And, if you prefer the FirefoxBinary approach:


from selenium import webdriver

from selenium.webdriver.firefox.firefox_binary import FirefoxBinary

binary = FirefoxBinary('C:\\Program Files\\Mozilla Firefox\\firefox.exe')

binary.add_command_line_options('-headless')

driver = webdriver.Firefox(firefox_binary=binary)

driver.get('https://www.example.com')

Both methods set Firefox to run in headless mode, so choose the one that suits your coding style. Just double-check that the path to the Firefox executable is accurate. Happy coding!