【问题标题】:How to download file from web using request module?如何使用请求模块从网络下载文件?
【发布时间】:2016-06-20 02:35:18
【问题描述】:

我正在使用python从网页下载文件,提交请求后,我得到如下标题:

>>> r.headers
{'Content-Disposition': 'attachment; filename="report20160619-013623.csv";',
 'Content-Transfer-Encoding': 'binary', 'Expires': '0',
'Keep-Alive': 'timeout=5, max=100', 'Server': 'Apache',
'Transfer-Encoding': 'chunked', 'Connection': 'Keep-Alive', 'Pragma': 'public',
'Cache-Control': 'must-revalidate, post-check=0, pre-check=0, private',
'Date': 'Sun, 19 Jun 2016 06:35:18 GMT', 'X-Frame-Options': 'SAMEORIGIN',
'Content-Type': 'application/octet-stream'}

我的问题是如何使用request 模块下载report20160619-013623.csv

我在网上搜索,有一些解决方案可以下载给定该文件的特定 URL 的文件,但是,在我的情况下,该文件是通过单击“下载为 excel”之类的内容在网络上生成的。我怎么知道文件在哪里?

【问题讨论】:

    标签: python download python-requests


    【解决方案1】:

    您将阅读响应,然后将其作为文件写入您指定的位置。

    csv = r.text
    
    outfile = open('/path/to/my.csv', 'w')
    outfile.write(csv)
    outfile.close()
    

    【讨论】:

    • OP 指定他想使用requests 模块...
    • @GeorgeWang 在我的原始回复中,我使用“example.com/downloads.csv”来表示您正在下载的文件的路径,但您已经有了包含该文件的回复。
    • @3kt 好点 - 我已经重写了我的回复以使用请求模块
    • @climmunk,非常感谢您的帮助。我想我能感觉到它是如何工作的。但是要确认一下,这里的report20160619-013623.csv是没用的,对吧?可以用自定义名称替换吗?
    • 这是默认的文件名,可以使用也可以更改。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-08-30
    • 1970-01-01
    • 2016-04-02
    • 2021-11-23
    相关资源
    最近更新 更多