python 属性错误:“Options”对象没有属性“binary”错误通过Selenium使用GeckoDriver调用Headless Firefox

omhiaaxx  于 2023-05-12  发布在  Python
关注(0)|答案(3)|浏览(326)
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”时,代码工作正常。我该怎么做才能解决这个问题?

rqqzpn5f

rqqzpn5f1#

而不是使用firefox_options对象,你需要使用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")

参考资料

您可以在以下内容中找到一些相关的详细讨论:

  • 如何使用Python在Selenium中以编程方式使Firefox无头?
shstlldc

shstlldc2#

--headless参数目前在Firefox(geckodriver)中运行良好。
如果你得到标题中提到的错误,那么你可能不小心创建或传递了一个基于Chrome的Options对象,而不是基于Firefox的Options对象。
为了避免这种错误,最好为它们都创建一个导入别名,以便更容易区分它们。

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

nuypyhwy3#

这四条线帮助了我:

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

...

    options = FirefoxOptions()
    options.add_argument("--headless")
    driver = webdriver.Firefox(firefox_options=options)

如果仍然出现错误,可以尝试将第四行替换为driver = webdriver.Firefox(options=options)
参考-Unable to invoke firefox headless

相关问题