Unable to invoke firefox headless

2020-07-22 10:29发布

问题:

I would like to know why i'm getting the following error message and how can i fix it:

Traceback (most recent call last): File "teste.py", line 30, in <\module>

main()

File "teste.py", line 24, in main

driver = connectFirefox(defineOptions())

File "teste.py", line 18, in connectFirefox

driver = webdriver.Firefox(firefox_options=options)

File "/usr/lib/python3.6/site-packages/selenium/webdriver/firefox /webdriver.py", line 125, in init

if options.binary is not None:

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

My code:

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

def defineOptions():
    options = Options()
    options.add_argument("--headless")
    return options

def connectChrome(options):
    chromeDriverPath = "/usr/bin/chromedriver"
    driver = webdriver.Chrome(chromeDriverPath, chrome_options=options)
    print("Chrome Headless Browser Invoked")
    return driver

def connectFirefox(options):
    driver = webdriver.Firefox(firefox_options=options)
    print("Firefox Headless Browser Invoked")
    return driver

def main():
    #driver = connectChrome(defineOptions())
    driver = connectFirefox(defineOptions())
    driver.get("https://www.archlinux.org/")
    print("Headless Browser closing")
    driver.quit()
#------------------------------------------------------------------------#

main()

What I'm trying to do is write a code where I can easily choose Chrome or Firefox headless.

回答1:

I solved my problem. Here the code:

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

def connectChrome():
    options = ChromeOptions()
    options.add_argument("--headless")
    chromeDriverPath = "/usr/bin/chromedriver"
    driver = webdriver.Chrome(chromeDriverPath, chrome_options=options)
    print("Chrome Headless Browser Invoked")
    return driver

def connectFirefox():
    options = FirefoxOptions()
    options.add_argument("--headless")
    driver = webdriver.Firefox(firefox_options=options)
    print("Firefox Headless Browser Invoked")
    return driver

def main():
    #driver = connectChrome()
    driver = connectFirefox()
    driver.get("https://www.archlinux.org/")
    print("Headless Browser closing")
    driver.quit()
#------------------------------------------------------------------------#
main()