首页 > 解决方案 > python selenium firefox - add_extension 不工作

问题描述

尝试将 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 版本似乎正在运行……</p>

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 贬值了吗?

标签: pythonseleniumselenium-webdriverselenium-firefoxdriver

解决方案


因为,由于某种原因,chrome 的add_extension作品,但 firefox 的add_extension作品(目前)不起作用……这是我为 firefox 添加扩展的解决方法。

  1. 通过创建一个新的 Firefox 配置文件right click windows start button > run > firefox.exe -P
  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 配置文件,而不是.crx直接调用。

  1. 将扩展安装到 chrome 的默认配置文件中。
  2. 导航到C:\Users\User\AppData\Local\Google\ChromechromesUser Data文件夹所在的位置。直接调用这个文件夹(绝对路径)或者重命名,调用相对路径。我已将其重命名为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'})
    

推荐阅读