【问题标题】:downloading an excel file from the web in python用python从网上下载一个excel文件
【发布时间】:2014-10-14 10:36:13
【问题描述】:

我有以下网址:

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文件?

【问题讨论】:

标签: python download


【解决方案1】:

我建议使用requests:

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

【讨论】:

    【解决方案2】:

    添加到 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)
    

    【讨论】:

      【解决方案3】:

      这会将 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
      

      【讨论】:

      • 我使用了您的代码并得到了错误。我通过更改为urllib.request.urlretrieve(dls, "test.xls") 解决了这个问题
      【解决方案4】:

      两个问题,一个是代码(如下),另一个是 URL 错误。 (现代)网络浏览器会自动将“http://www.muellerindustries.com/uploads/pdf/UWSPD0114.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) 
      

      这让我得到了文件。

      【讨论】:

        猜你喜欢
        • 2017-01-30
        • 1970-01-01
        • 2017-11-28
        • 1970-01-01
        • 2022-07-12
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2010-11-06
        相关资源
        最近更新 更多