[英]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文檔。
工作方案
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)
我可以按原樣下載文件。
當您想直接下載文件時,可以使用shutil.copyfileobj()
:
https://docs.python.org/2/library/shutil.html#shutil.copyfileobj
您已經將stream=True
傳遞給requests
,這是獲取類似文件的對象所需要的。 只需將其作為源傳遞給copyfileobj()
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.