AttributeError: 'Options' object has no attribute 'binary' error invoking Headless Firefox using GeckoDriver through Selenium

AttributeError: 'Options' object has no attribute 'binary' error invoking Headless Firefox using GeckoDriver through Selenium

options = FirefoxOptions()
options.add_argument("--headless")


driver = webdriver.Firefox(firefox_options=options, executable_path='/Users/toprak/Desktop/geckodriver') 
driver.get("https://twitter.com/login?lang=en")

当我尝试 运行 我的代码时,出现此错误:

Warning (from warnings module):
  File "/Users/toprak/Desktop/topla.py", line 19
    driver = webdriver.Firefox(firefox_options=options, executable_path='/Users/toprak/Desktop/geckodriver')
DeprecationWarning: use options instead of firefox_options
Traceback (most recent call last):
  File "/Users/toprak/Desktop/topla.py", line 19, in <module>
    driver = webdriver.Firefox(firefox_options=options, executable_path='/Users/toprak/Desktop/geckodriver')
  File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/selenium/webdriver/firefox/webdriver.py", line 137, in __init__
    if options.binary is not None:
AttributeError: 'Options' object has no attribute 'binary'

当我删除关于选项的行并取出“firefox_options=options”时,代码工作正常。我应该怎么做才能解决这个问题?

您需要使用 options 对象,而不是使用 firefox_options 对象。此外,您需要使用 headless 属性。所以你的有效代码块将是:

options = FirefoxOptions()
options.headless = True

driver = webdriver.Firefox(executable_path='/Users/toprak/Desktop/geckodriver', options=options) 
driver.get("https://twitter.com/login?lang=en")

参考资料

您可以在以下位置找到一些相关的详细讨论:

最近 --headless 参数在 Firefox (geckodriver) 中运行良好。

如果您遇到标题中提到的错误,那么您可能不小心创建或传递了 Chrome-based 选项 object 而不是 Firefox-based 选项 object.

为避免该错误,最好为它们创建一个导入别名,以便更容易区分它们。

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

chrome_options = ChromeOptions()
chrome_options.add_argument('--headless')
chrome_driver = webdriver.Chrome(executable_path = r"..\mypath\chromedriver.exe", options=chrome_options)

firefox_options = FirefoxOptions()
firefox_options.add_argument('--headless')
firefox_driver = webdriver.Firefox(executable_path = r"..\mypath\geckodriver.exe", options=firefox_options)