2016-12-05 140 views
0

我需要從外部來源下載一個文件下載的二進制文件,我使用基本身份驗證登錄到URL使用Python請求模塊

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在同一個會話中下載單詞文檔。

+0

所以通過它的聲音的第一步是罰款(返回你想要的網址?)。你沒有做的是從第二個響應中提取數據。 「data = requests.get('<要下載附件的API URL>',stream = True)」應該可能類似於「data = requests.get('',stream = True) .text「?如果它仍然不起作用,請嘗試此操作並編輯該問題 –

+1

http://docs.python-requests.org/en/master/user/advanced/#session-objects並且可能還會在第二個請求中傳遞'auth'作爲好? – Jasper

+0

我建議您重新閱讀Requests Quickstart文檔。要從返回的Response對象獲取_binary_數據,您需要訪問其[[.content]屬性(http://docs.python-requests.org/en/master/user/quickstart/#binary-response-content)屬性。 –

回答

0

當你要下載一個文件,直接就可以使用shutil.copyfileobj()

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

你已經逝去的stream=Truerequests這是你需要獲得一個類似文件的對象回來什麼。只需將其作爲copyfileobj()的來源即可。

0

工作液

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) 

我能夠下載該文件,因爲它是。