DeprecationWarning: firefox_binary 已被弃用,请在 Selenium Python 中使用参数 firefox_binary 传入服务对象

DeprecationWarning: firefox_binary has been deprecated, please pass in a Service object using the argument firefox_binary in Selenium Python

使用以下代码,在 Mac 上,我尝试使用 Python 和 Selenium 启动 Tor 浏览器:

from selenium import webdriver
from selenium.webdriver.firefox.firefox_binary import FirefoxBinary
from selenium.webdriver.firefox.service import Service
from selenium.webdriver.firefox.options import Options
from webdriver_manager.firefox import GeckoDriverManager
from selenium.webdriver.firefox.firefox_profile import FirefoxProfile
import os
import time

binary = '/Applications/Tor Browser.app/Contents/MacOS/firefox'

# binary location
if os.path.exists(binary) is False:
    raise ValueError("The binary path to Tor firefox does not exist.")
firefox_binary = FirefoxBinary(binary)

browser = None

def get_browser(binary=None, options=None):
    global browser
    # only one instance of a browser opens
    if not browser:
        browser = webdriver.Firefox(firefox_binary=binary, options=options)
    return browser

browser = get_browser(binary=firefox_binary)

time.sleep(20)
browser.get("http://whosebug.com")
time.sleep(10)
html = browser.page_source
print(html)

这确实有效,但我收到以下警告:

DeprecationWarning: firefox_binary has been deprecated, please pass in a Service object
  browser = webdriver.Firefox(firefox_binary=binary,options=options)

我搜索了传递此 Service 对象的方法,但没有任何效果:实质上,我尝试以其他浏览器的方式传递对象。

事实上,虽然其他浏览器有记录 Service class,但即使我可以毫无错误地导入 from selenium.webdriver.firefox.service a Service class,webdriver 构造函数也没有没有任何服务对象或没有记录。

感谢任何帮助。

这个错误信息...

DeprecationWarning: firefox_binary has been deprecated, please pass in a Service object
  browser = webdriver.Firefox(firefox_binary=binary,options=options)

...表示参数 firefox_binary 现在 已弃用 你需要传递一个 Service 对象。


详情

根据 webdriver.py

,此错误与 webdriver 的当前实现内联
if firefox_binary:
    warnings.warn('firefox_binary has been deprecated, please pass in a Service object',
                  DeprecationWarning, stacklevel=2)

解决方案

根据Selenium v4.0 Beta 1

  • Deprecate all but Options and Service arguments in driver instantiation. (#9125,#9128)

所以你必须使用 binary_location 属性 而不是 firefox_binary 并通过它通过 FirefoxOptions() 的实例如下:

from selenium import webdriver
from selenium.webdriver.firefox.service import Service

option = webdriver.FirefoxOptions()
option.binary_location = r'/Applications/Tor Browser.app/Contents/MacOS/firefox'
driverService = Service('/path/to/geckodriver')
driver = webdriver.Firefox(service=driverService, options=option)
driver.get("https://www.google.com")

参考资料

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

  • Use Selenium with Brave Browser pass service object written in python