python Response iter_content


Response.iter_content

原始響應內容

在罕見的情況下,你可能想獲取來自服務器的原始套接字響應,那么你可以訪問 r.raw。 如果你確實想這么干,那請你確保在初始請求中設置了 stream=True。具體你可以這么做:

>>> r = requests.get('https://github.com/timeline.json', stream=True)
>>> r.raw
<requests.packages.urllib3.response.HTTPResponse object at 0x101194810>
>>> r.raw.read(10)
'\x1f\x8b\x08\x00\x00\x00\x00\x00\x00\x03'

但一般情況下,你應該以下面的模式將文本流保存到文件

with open(filename, 'wb') as fd: for chunk in r.iter_content(chunk_size): fd.write(chunk)

使用 Response.iter_content 將會處理大量你直接使用 Response.raw 不得不處理的。 當流下載時,上面是優先推薦的獲取內容方式。


和tqdm進度條的結合

tqdm進度條的使用,for data in tqdm(iterable) 
Response.iter_content是可迭代對象

def dd(url,filename):#傳入url,以及下載文件的全路徑filename #url = "http://www.jxepb.gov.cn/resource/uploadfile/file/20160307/20160307083510567.xls" response = requests.get(url, stream=True) #用response儲存在獲取url的響應 with open(filename, "wb") as handle: #打開本地文件夾路徑filename,以二進制寫入,命名為handle for data in tqdm(response.iter_content()): #tqdm進度條的使用,for data in tqdm(iterable) handle.write(data) #在handle對象中寫入data數據


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM