[英]downloading an excel file from the web in python
我有以下網址:
dls = "http://www.muellerindustries.com/uploads/pdf/UW SPD0114.xls"
我嘗試下載文件:
urllib2.urlopen(dls, "test.xls")
這生成了一個名為“test.xls”的文件,但這顯然是一個 html 文件。 如果我在 firefox 中打開 html 文件,它會打開一個 excel 文件,但如果我在 excel 中打開文件,它絕對不是我要找的 excel 文件。
如果我有一個像上面這樣的網址,我如何讓python將excel文件下載為excel文件?
我建議使用請求:
import requests
dls = "http://www.muellerindustries.com/uploads/pdf/UW SPD0114.xls"
resp = requests.get(dls)
output = open('test.xls', 'wb')
output.write(resp.content)
output.close()
要安裝請求:
pip install requests
添加 Fedalto 的請求建議 (+1),但使用上下文管理器使其更加 Pythonic:
import requests
dls = "http://www.muellerindustries.com/uploads/pdf/UW SPD0114.xls"
resp = requests.get(dls)
with open('test.xls', 'wb') as output:
output.write(resp.content)
這會將 excel 文件保存在運行腳本的同一文件夾中。
import urllib
dls = "http://www.muellerindustries.com/uploads/pdf/UW SPD0114.xls"
urllib.request.urlretrieve(dls, "test.xls") # For Python 3
# urllib.urlretrieve(dls, "test.xls") # For Python 2
兩個問題,一個是代碼(如下),另一個是 URL 錯誤。 (現代)網絡瀏覽器會自動將“ http://www.muellerindustries.com/uploads/pdf/UW SPD0114.xls”更正為“ http://www.muellerindustries.com/uploads/pdf/UW%20SPD0114.xls "但 Python 沒有。
這段代碼在 python 3.x 上對我有用
import urllib
outfilename = "test.xls"
url_of_file = "http://www.muellerindustries.com/uploads/pdf/UW%20SPD0114.xls"
urllib.request.urlretrieve(url_of_file, outfilename)
這讓我得到了文件。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.