Python Selenium Firefox - add_extension不起作用

3

尝试将uBlock添加到浏览器会话中,但它没有起作用。

import selenium
from selenium.webdriver.firefox.firefox_binary import FirefoxBinary
from selenium.webdriver.firefox.options import Options as options


def establish_browser(type, hide):
    browser = ''
    if type == 'firefox':
        ops = options()
        ops.add_argument("--headless") if hide is True else ops.add_argument("--head")
        profile = selenium.webdriver.FirefoxProfile()
        profile.add_extension(extension='uBlock0@raymondhill.net.xpi')
        browser = selenium.webdriver.Firefox(firefox_profile=profile, executable_path='geckodriver.exe', options=ops, firefox_binary=FirefoxBinary('C:/Program Files/Mozilla Firefox/firefox.exe'))
    return browser

browser = establish_browser('firefox', False)

这应该如何更改以使uBlock起作用?
更新
Chrome版本似乎正在工作中...
if type == 'chrome':
    from selenium.webdriver.chrome.options import Options as options
    ops = options()
    ops.add_argument("--headless") if hide is True else ops.add_argument("--head")
    ops.add_extension("ublock.crx")
    browser = selenium.webdriver.Chrome(executable_path='chromedriver.exe', options=ops, desired_capabilities={'binary_location': 'C:/Program Files (x86)/Google/Chrome/Application/chrome.exe'})

Firefox被淘汰了吗?

1
你在 geckodriver 问题跟踪器上创建了关于这个问题的问题吗? - CodeSamurai777
我可能会这样做,明天我会调查一下。 - Rhys
2个回答

3

由于某些原因,Chrome的add_extension可用,但Firefox的add_extension目前不可用...这里是我为Firefox添加扩展的解决方法。

  1. 通过右键单击Windows开始按钮>运行>firefox.exe -P创建一个新的Firefox配置文件
  2. 然后添加任何您想要的扩展程序,如ublock、adblock plus等
  3. 使用以下代码调用您的配置文件文件夹

profile = selenium.webdriver.FirefoxProfile("C:/test")

browser = selenium.webdriver.Firefox(firefox_profile=profile, options=ops)

显然,对于这个解决方法,profile.add_extension()并不是必需的。

更新!- 添加了Chrome配置文件

出于对称性的考虑,我已经更新了Chrome示例代码,使用Chrome配置文件而不是直接调用.crx文件。

  1. install extensions onto chrome's default profile.
  2. navigate to C:\Users\User\AppData\Local\Google\Chrome or where-ever chromes User Data folder is located. Call this folder directly (absolute path) or rename it and call the relative path. I have renamed it to chrome_profile:

    ops = options()
    ops.add_argument("--headless") if hide is True else ops.add_argument("--head")
    ops.add_argument('user-data-dir=chrome_profile')
    ops.add_argument('--profile-directory=Default')
    ops.add_argument("--incognito")
    browser = selenium.webdriver.Chrome(executable_path='chromedriver.exe', options=ops, desired_capabilities={'binary_location': 'C:/Program Files (x86)/Google/Chrome/Application/chrome.exe'})
    

0

为了补充@Rhys的解决方案,一个更简单的方法可能是从官方文档中选择以下选项,可以按预期工作:

driver = webdriver.Firefox('path/to/executable')
driver.install_addon('~/path/to/addon.xpi')

虽然这个链接可能回答了问题,但最好在此处包含答案的基本部分并提供参考链接。如果链接页面更改,仅有链接的答案可能会失效。-【来自审查】 - user11717481
同意,这就是为什么下面包含必要的代码。 - Luis

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接