繁体   English   中英

用python从网上下载一个excel文件

[英]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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM