【问题标题】:Python: How to add Firefox extensions in Selenium 4Python:如何在 Selenium 4 中添加 Firefox 扩展
【发布时间】:2022-01-07 03:00:26
【问题描述】:

我使用的最后一个 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() 对象一起使用显然不是添加扩展的正确方法。但是,我找不到正确的方法。

有可能创建一个FirefoxProfile 并在那里添加扩展名,但至少这似乎给出了一个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 中添加扩展的正确方法是什么?

【问题讨论】:

    标签: python selenium selenium-webdriver selenium-firefoxdriver selenium4


    【解决方案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

    【讨论】:

      猜你喜欢
      • 2018-10-25
      • 1970-01-01
      • 2019-03-07
      • 2021-11-27
      • 2019-12-27
      • 2019-02-08
      • 1970-01-01
      • 2021-11-02
      • 1970-01-01
      相关资源
      最近更新 更多