火狐中的文件下载对话框

3 投票
1 回答
1862 浏览
提问于 2025-04-17 09:08

我正在用Selenium和Python编程,使用Firefox浏览器,想要自动开始下载并保存文件。我已经做了所有的准备,但就是无法下载CSV文件。我的Python版本是2.6.6,Selenium是最新版本。

fp = webdriver.FirefoxProfile()
fp.set_preference("browser.download.folderList",2)
fp.set_preference("browser.download.manager.showWhenStarting",False)
fp.set_preference("browser.download.dir",getcwd())
fp.set_preference("browser.helperApps.neverAsk.saveToDisk","text/csv")
browser = webdriver.Firefox(firefox_profile=fp)

我用了这个方法,但没有下载到文件,也没有出现任何错误。有没有人能帮帮我?

我的文件是 ![我到这里为止,下一步是用Selenium和Python程序下载它][1]

如果有人有解决办法,请帮帮我。

1 个回答

2

这里有一个完整的例子,适用于我使用的Firefox 3.6.24和8.0.1版本。

#!/Library/Frameworks/Python.framework/Versions/2.7/bin/python2.7
from selenium import webdriver

profile = webdriver.FirefoxProfile()
profile.set_preference('browser.download.dir',"/tmp/webdriver-downloads")
profile.set_preference('browser.download.folderList',2)
profile.set_preference('browser.helperApps.neverAsk.saveToDisk',"text/csv")
driver = webdriver.Firefox(profile)
base_url = "http://localhost/"
driver.get(base_url + "/text.csv")

你确定你的网络服务器返回的是text/csv作为Mime类型吗?一种验证的方法是使用curl来确认HTTP响应中的Content-Type头部是否是你所期望的:

$ curl -v http://localhost/text.csv
* About to connect() to localhost port 80 (#0)
*   Trying 127.0.0.1... connected
> GET /text.csv HTTP/1.1
> User-Agent: curl/7.23.1 (x86_64-apple-darwin10.8.0) libcurl/7.23.1 OpenSSL/1.0.0e zlib/1.2.5 libidn/1.22
> Host: localhost
> Accept: */*
> 
< HTTP/1.1 200 OK
< Date: Wed, 28 Dec 2011 17:10:46 GMT
< Server: Apache/2.2.20 (Unix) mod_ssl/2.2.20 OpenSSL/0.9.8r DAV/2
< Last-Modified: Wed, 28 Dec 2011 17:05:47 GMT
< ETag: "291f98-0-4b52a02cbb0c0"
< Accept-Ranges: bytes
< Content-Length: 0
< Cache-Control: max-age=300
< Expires: Wed, 28 Dec 2011 17:15:46 GMT
< Content-Type: text/csv
< 
* Connection #0 to host localhost left intact
* Closing connection #0

撰写回答