使用 Python 请求模块下载二进制文件

Download a binary file using Python requests module

我需要从外部源下载文件,我正在使用基本身份验证登录 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 文档。

当你想直接下载文件时可以使用shutil.copyfileobj():

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

您已经将 stream=True 传递给 requests,这是您需要返回类似文件的对象的方法。只需将其作为来源传递给 copyfileobj().

工作解决方案

import requests
import shutil

response = requests.get('<url>', auth=('<username>', '<password>'))
data = response.json()
html = data['list'][0]['attachments'][0]['url']
print (html)
data = requests.get('<url>', auth=('<username>', '<password>'), stream=True)
with open("C:/myfile.docx", 'wb') as f:
    data.raw.decode_content = True
    shutil.copyfileobj(data.raw, f) 

我可以按原样下载文件。