Search code examples
seleniumpython-3.8ubuntu-20.04selenium-firefoxdriverfirefox-driver

Python: Function equivalent to chromedriver in firefoxdriver. chromedriver --> firefoxdriver (firefoxdriver gives me syntax error)


I have this two functions:

def get_chromedriver(headless = False):
    import os
    from selenium import webdriver
    from selenium.webdriver.chrome.options import Options
    options = Options()
    options.binary_location = '/usr/bin/google-chrome'
    options.add_argument('user-data-dir=' + os.environ['HOME'] + '/.config/chromedriver')
    options.add_experimental_option('detach', True)
    options.add_experimental_option('excludeSwitches', ['enable-automation'])
    options.add_experimental_option('useAutomationExtension', False)
    options.headless = headless
    driver = webdriver.Chrome(executable_path='/usr/bin/chromedriver', options=options)
    return driver

def get_firefoxdriver(headless = False):
    import os
    from selenium import webdriver
    from selenium.webdriver.firefox.options import Options
    options = Options()
    options.binary_location = '/usr/bin/firefox'
    options.add_argument('user-data-dir=' + os.environ['HOME'] + '/.config/firefoxdriver')
    options.add_experimental_option('detach', True)
    options.add_experimental_option('excludeSwitches', ['enable-automation'])
    options.add_experimental_option('useAutomationExtension', False)
    options.headless = headless
    driver = webdriver.Firefox(executable_path='/usr/bin/geckodriver', options=options)
    return driver

get_chromedriver function works perfectly but not get_firefoxdriver, which is a copy of the get_chromedriver function.
How can I make the get_firefoxdriver function functionally equivalent to the get_chromedriver function, except for the paths, the webdriver and the browser used?


Solution

  • Firefox webdriver does not have the same instance methods as the Chrome webdriver. I see that in your Firefox driver creation function you are calling "detach" and "exludeSwitches" options, however if you take a look at the Firefox documentation you won't find those options whereas the same are available in the Chrome documentation.

    There are pros and cons in using each driver, and as in every case the solution should match the use case.