我想在Python中使用Selenium從網站下載文件。爲了做到這一點,我已經閱讀了我需要更改我的Firefox配置文件中的設置,以避免打開下載對話窗口。我在下面提供了示例代碼。這段代碼在家裏工作得非常好,但它不能在我的工作PC上正常工作。我懷疑Python不能改變Firefox配置文件的設置,即使下面的代碼不會拋出錯誤但工作正常,最後打開下載對話窗口。Python中的Selenium下載文件:即使在設置Firefox配置文件後,下載窗口打開
from selenium import webdriver
import os
profile = webdriver.FirefoxProfile("C:\\Users\\Ric\\Documents\\Python Scripts\\FirefoxProfileCopies\\ric.copy")
profile.set_preference('browser.download.folderList', 2)
profile.set_preference('browser.download.manager.showWhenStarting', False)
profile.set_preference('browser.download.dir', os.getcwd())
profile.set_preference('browser.helperApps.neverAsk.saveToDisk',('application/vnd.ms-excel'))
browser = webdriver.Firefox(profile)
browser.get("http://www.sample-videos.com/download-sample-xls.php")
elem1 = browser.find_element_by_css_selector(".push-form > table:nth-child(2) > tbody:nth-child(2) > tr:nth-child(4) > td:nth-child(4) > a:nth-child(1)")
elem1.click()
此代碼完全適用於我的Firefox及其在家中的個人資料,但與我的電腦無關。有人知道這可能是爲什麼嗎?先謝謝你。
編輯
我試圖從微軟的網頁添加所有MIME
類型,不過,下載管理器窗口中打開。當停止代碼開放下載鏈接,想看看在使用Firefox的配置文件的設置與about:config
顯示以下值前執行:
您確定要在正確的文件夾中搜索下載的文件嗎?嘗試用'profile.set_preference('browser.download.dir','C:\\ Users \\ Ric \\ Desktop')替換'profile.set_preference('browser.download.dir',os.getcwd() )' – Andersson
你好安德森,謝謝你的想法。我試過了,文件確實沒有下載,它並沒有出現在我的桌面上。 Firefox打開下載窗口,因此不會下載。還有什麼想法?我欣賞每一個提示。 – rashid
檢查文件'MIME'類型是否真的是'application/vnd.ms-excel',你可能需要添加更多的'MIME'類型 – Andersson