首页 文章

Python Selenium:设置Firefox首选项失败

提问于
浏览
2

我正在尝试使用selenium在网页中自动下载文件 . 例如,我们可以考虑从https://github.com/mozilla/geckodriver/releases尝试自动下载geckodriver .

我的python代码如下:

这是我使用的代码:

profile = webdriver.FirefoxProfile()
profile.set_preference("browser.download.folderList",2)
profile.set_preference("browser.download.manager.showWhenStarting",False)
profile.set_preference("browser.download.dir", path)
profile.set_preference("browser.download.downloadDir", path)
profile.set_preference("browser.download.defaultFolder", path)
profile.set_preference("browser.helperApps.alwaysAsk.force", False)
profile.set_preference("browser.helperApps.neverAsk.saveToDisk", "application/x-gzip, application/tar+gzip, application/x-gtar, application/x-compressed")
profile.set_preference("pdfjs.disabled", True)
profile.update_preferences()
browser =  webdriver.Firefox(profile)
browser.get('https://github.com/mozilla/geckodriver/releases')

sleep(5)
try:
    field = browser.find_element_by_xpath("//ul[@class='release-downloads']//li/a/strong[contains(text(),'geckodriver-v0.11.1-linux64.tar.gz')]")
    if(field != None):
    field.click()
    find = True
except Exception,e: 
    print str(e)

我的问题是如果我尝试这个代码我得到了firefox的弹出下载:

enter image description here

我想也许我设置了偏好browser.helperApps.neverAsk.saveToDisk的错误值,所以我尝试下载zip文件,但我遇到了同样的问题 . 然后我看了一下about:config但不幸的是我发现参数设置为默认值 . 例如,我发现browser.download.folderList的值为1但不是2:

enter image description here

browser.helperApps.neverAsk.saveToDisk也是null值,并且browser.download.dir不存在 .

Edit: Download without setting preferences

然后我尝试不使用此代码设置首选项:

browser =  webdriver.Firefox()
browser.get('https://github.com/mozilla/geckodriver/releases')

sleep(5)
try:
    field = browser.find_element_by_xpath("//ul[@class='release-downloads']//li/a/strong[contains(text(),'geckodriver-v0.11.1-linux64.tar.gz')]")
    if(field != None):
    field.click()
    find = True
except Exception,e: 
    print str(e)
    pass

但我得到了同样的问题,就像我删除的设置首选项部分没有任何影响 . 但考虑到如果我手动打开Firefox并在下载链接中手动点击,我可以直接使用firefox的确认弹出窗口下载文件,没有任何问题 .

我的代码中有错误吗?或者有什么问题?

开发环境:Python2.7,selenium3.0.1,Firefox 49 .

1 回答

  • 0

    您应该使用分号来分隔mime类型:

    profile.set_preference(“browser.helperApps.neverAsk.saveToDisk”,“application / x-gzip; application / tar gzip; application / x-gtar; application / x-compressed”)

相关问题