2016-11-17 89 views
2

我試圖在使用硒的網頁中自動下載文件。 我們可以考慮例如我會嘗試從https://github.com/mozilla/geckodriver/releases自動下載geckodriver。Python Selenium:設置Firefox偏好設置失敗

我的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文件e但我得到了同樣的問題。然後我看了about:config,但不幸的是我發現參數設置爲默認值。例如,我發現browser.download.folderList的值是1而不是2:

enter image description here

也browser.helperApps.neverAsk.saveToDisk是空值,和browser.download.dir不存在。

編輯:沒有設定的喜好下載

然後我嘗試不使用此代碼設置首選項:

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,火狐49

+0

我相信我在這裏解決了這個問題[Python Selenium Download Profile](http://stackoverflow.com/問題/ 41644381/python-set-firefox-preferences-for-selenium-download-location/41683377#41683377) 。 –

回答

0

你應該用分號來分隔MIME類型:

profile.set_preference( 「browser.helperApps.neverAsk.saveToDisk」,「 application/x-gzip; application/tar + gzip; application/x-gtar; application/x-compressed「)