1

我使用的最后一个 Selenium 版本是 3.141.0。

我现在正在过渡到 Selenium 4,并且试图弄清楚如何在 Python 3 中为 Firefox 添加扩展。

以前,这样的事情会起作用:

from selenium import webdriver

profile = webdriver.FirefoxProfile(profile_path)
profile.add_extension('adblock_plus-3.10.2-an+fx.xpi')
driver = webdriver.Firefox(profile)

在尝试进行 Selenium 4 显然需要的一些调整时,我尝试了以下代码:

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

options = Options()
options.set_preference('profile', profile_path)
options.add_extension('adblock_plus-3.10.2-an+fx.xpi')

service = Service('/usr/local/bin/geckodriver')

driver = webdriver.Firefox(options=options, service=service)

在 Selenium 4.1.0 中,这给出了AttributeError

options.add_extension('adblock_plus-3.10.2-an+fx.xpi')
AttributeError: 'Options' object has no attribute 'add_extension'

.add_extension()与对象一起使用Options()显然不是添加扩展的正确方法。但是,我找不到正确的方法。

有可能创建 aFirefoxProfile并在其中添加扩展名,但至少这似乎给出了 a DeprecationWarning,我不知道它是否会起作用:

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

profile = webdriver.FirefoxProfile(profile_path)
profile.add_extension('adblock_plus-3.10.2-an+fx.xpi')

options = Options()
options.set_preference('profile', profile_path)

service = Service('/usr/local/bin/geckodriver')

driver = webdriver.Firefox(profile, options=options, service=service)
DeprecationWarning: profile has been deprecated, please pass in an Options object
  driver = webdriver.Firefox(profile, options=options, service=service)

在 Selenium 4 for Firefox 中添加扩展的正确方法是什么?

4

1 回答 1

1

您应该能够直接在 Webdriver 上添加扩展

driver = webdriver.Firefox(service=service)
driver.install_addon('adblock_plus-3.10.2-an+fx.xpi')

https://www.selenium.dev/selenium/docs/api/py/webdriver_firefox/selenium.webdriver.firefox.webdriver.html#selenium.webdriver.firefox.webdriver.WebDriver.install_addon

于 2021-11-30T12:16:10.243 回答