新聞中心
通常,我們都會用 requests 庫去下載,這個庫用起來太方便了。

成都創(chuàng)新互聯(lián)公司專注于企業(yè)全網(wǎng)整合營銷推廣、網(wǎng)站重做改版、鳩江網(wǎng)站定制設(shè)計、自適應(yīng)品牌網(wǎng)站建設(shè)、H5響應(yīng)式網(wǎng)站、商城網(wǎng)站建設(shè)、集團公司官網(wǎng)建設(shè)、成都外貿(mào)網(wǎng)站制作、高端網(wǎng)站制作、響應(yīng)式網(wǎng)頁設(shè)計等建站業(yè)務(wù),價格優(yōu)惠性價比高,為鳩江等各大城市提供網(wǎng)站開發(fā)制作服務(wù)。
方法一
使用以下流式代碼,無論下載文件的大小如何,Python 內(nèi)存占用都不會增加:
def download_file(url):
local_filename = url.split('/')[-1]
# 注意傳入?yún)?shù) stream=True
with requests.get(url, stream=True) as r:
r.raise_for_status()
with open(local_filename, 'wb') as f:
for chunk in r.iter_content(chunk_size=8192):
f.write(chunk)
return local_filename
如果你有對 chunk 編碼的需求,那就不該傳入 chunk_size 參數(shù),且應(yīng)該有 if 判斷。
def download_file(url):
local_filename = url.split('/')[-1]
# 注意傳入?yún)?shù) stream=True
with requests.get(url, stream=True) as r:
r.raise_for_status()
with open(local_filename, 'w') as f:
for chunk in r.iter_content():
if chunk:
f.write(chunk.decode("utf-8"))
return local_filename
iter_content[1] 函數(shù)本身也可以解碼,只需要傳入?yún)?shù) decode_unicode = True 即可。另外,搜索公眾號頂級Python后臺回復(fù)“進階”,獲取一份驚喜禮包。
請注意,使用 iter_content 返回的字節(jié)數(shù)并不完全是 chunk_size,它是一個通常更大的隨機數(shù),并且預(yù)計在每次迭代中都會有所不同。
方法二
使用 Response.raw[2] 和 shutil.copyfileobj[3]
import requests
import shutil
def download_file(url):
local_filename = url.split('/')[-1]
with requests.get(url, stream=True) as r:
with open(local_filename, 'wb') as f:
shutil.copyfileobj(r.raw, f)
return local_filename
這將文件流式傳輸?shù)酱疟P而不使用過多的內(nèi)存,并且代碼更簡單。
注意:根據(jù)文檔,Response.raw 不會解碼,因此如果需要可以手動替換 r.raw.read 方法
response.raw.read = functools.partial(response.raw.read, decode_content=True)
速度
方法二更快。方法一如果 2-3 MB/s 的話,方法二可以達到近 40 MB/s。
參考資料
[1]iter_content: https://requests.readthedocs.io/en/latest/api/#requests.Response.iter_content
[2]Response.raw: https://requests.readthedocs.io/en/latest/api/#requests.Response.raw
[3]shutil.copyfileobj: https://docs.python.org/3/library/shutil.html#shutil.copyfileobj
文章標(biāo)題:Python下載大文件,哪種方式速度更快!
本文鏈接:http://www.dlmjj.cn/article/dphgjgc.html


咨詢
建站咨詢
