使用Python请求模块下载二进制文件 [英] Download a binary file using Python requests module

查看:128
本文介绍了使用Python请求模块下载二进制文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要从外部来源下载文件,我正在使用基本身份验证登录到URL

I need to download a file from an external source, I am using Basic authentication to login to the URL

import requests
response = requests.get('<external url', auth=('<username>', '<password>'))
data = response.json()
html = data['list'][0]['attachments'][0]['url']
print (html)
data = requests.get('<API URL to download the attachment>', auth=('<username>', '<password>'), stream=True)
print (data.content) 

我的输出低于

<url to download the binary data> 
\x00\x00\x13\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x0f\xcb\x00\x00\x1e\x00\x1e\x00\xbe\x07\x00\x00.\xcf\x05\x00\x00\x00'

我希望该URL在同一会话中下载word文档。 / p>

I am expecting the URL to download the word document within the same session.

推荐答案

要直接下载文件时,可以使用 shutil.copyfileobj()

When you want to download a file directly you can use shutil.copyfileobj():

https://docs.python.org/2/library/shutil.html#shutil.copyfileobj

您已经通过了 stream = True 请求,这是获取类似文件的对象所需要的。只需将其作为源传递给 copyfileobj()

You already are passing stream=True to requests which is what you need to get a file-like object back. Just pass that as the source to copyfileobj().

这篇关于使用Python请求模块下载二进制文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆