代码之家  ›  专栏  ›  技术社区  ›  Rhys

python selenium firefox-add_扩展无效

  •  0
  • Rhys  · 技术社区  · 6 年前

    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 回复  |  直到 6 年前
        1
  •  1
  •   Rhys    6 年前

    因为某种原因,chrome的 add_extension 添加扩展名 不工作(目前)这里是我的解决办法,添加扩展到火狐。

    1. 通过创建新的firefox配置文件 right click windows start button > run > firefox.exe -P
    2. 然后添加任何你想要的扩展,ublock,adblock plus等等

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

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

    显然 profile.add_extension() 不是此解决方案的必备组件

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

    为了对称起见,我更新了chrome示例代码以使用chrome配置文件,而不是调用 .crx 直接。

    1. 导航到 C:\Users\User\AppData\Local\Google\Chrome User 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'})