pythonseleniumselenium-webdriverfirefox-profilefirefox-headless

Webdriver - Can't use headless mode in Firefox when using preferences


I want to launch Firefox headlessly through Selenium, but I can't seem to find a way to do so and keep my preferences at the same time.

from selenium import webdriver;
from selenium.webdriver import Firefox;

cProfile = webdriver.FirefoxProfile();
options = webdriver.FirefoxOptions();
dwnd_path = os.getcwd();

options.add_preference('browser.download.folderList', '2');
options.add_preference('browser.download.manager.showWhenStarting', 'false');
options.add_preference('browser.download.dir', 'dwnd_path');
options.add_preference('browser.helperApps.neverAsk.saveToDisk', 'application/octet-stream,application/vnd.ms-excel');

Running this, I will get this error:

Traceback (most recent call last):
  File "test.py", line 17, in <module>
    options.add_preference('browser.download.folderList', '2');
AttributeError: 'Options' object has no attribute 'add_preference'

Any ideas?


Solution

  • This error message...

    AttributeError: 'Options' object has no attribute 'add_preference'
    

    ...implies that an instance of Options doesn't supports the attribute add_preference.

    add_preference is supported by an instance of FirefoxProfile() only.

    You can find a detailed discussion to use add_preference with an instance of FirefoxProfile() in Python: Unable to download with selenium in webpage

    So your effective code block will be:

    from selenium import webdriver;
    from selenium.webdriver.firefox.options import Options
    
    cProfile = webdriver.FirefoxProfile();
    dwnd_path = os.getcwd();
    cProfile.add_preference('browser.download.folderList', '2');
    cProfile.add_preference('browser.download.manager.showWhenStarting', 'false');
    cProfile.add_preference('browser.download.dir', 'dwnd_path');
    cProfile.add_preference('browser.helperApps.neverAsk.saveToDisk', 'application/octet-stream,application/vnd.ms-excel');
    options = Options()
    options.headless = True
    driver = webdriver.Firefox(firefox_profile=cProfile, firefox_options=options, executable_path=r'C:\path\to\geckodriver.exe')
    

    Reference

    You can find a detailed discussion on how to use the headless argument through an instance of Options() class in How to make firefox headless programatically in Selenium with python?