http分片請求-python分片下載文件

源文件

http://theday.guohongfu.top/letter.txt內容爲abcdefghijklmnopqrstuvwxyzurl

獲取第20字節及之後的內容
import requests

url = 'http://theday.guohongfu.top/letter.txt'

headers1 = {
    'Range': "bytes=20-"  # 獲取 第20字節及之後的
}
response = requests.get(url, headers=headers1)
print('data={}'.format(response.content.decode()))  # abcdef


# 結果
#data=uvwxyz
設置 If-Match 判斷文件在兩次請求間是否發生了改變
import requests

url = 'http://theday.guohongfu.top/letter.txt'

headers1 = {
    'Range': "bytes=0-5"  # 獲取0-5 的字節
}

response = requests.get(url, headers=headers1)
print('data={}'.format(response.content.decode()))  # abcdef
# 獲得etag
req_etag = response.headers['ETag']
headers1['If-Match'] = req_etag # 判斷文件在兩次請求間是否發生了改變
headers1['Range'] = 'bytes=6-10'  # 獲取6-10字節的數據
response = requests.get(url, headers=headers1)
print('data={}'.format(response.content.decode()))  # ghijk

獲得結果:code

# data=abcdef
# data=ghijk
使用 Python 分片下載文件
import requests

mp4url = 'https://mp4.vjshi.com/2020-11-20/1c28d06e0278413bf6259ba8b9d26140.mp4'
response = requests.get(mp4url, stream=True)
with open('test.mp4', 'wb') as f:
    [f.write(chunk) for chunk in response.iter_content(chunk_size=512) if chunk]
每次以512字節進行下載數據,防止下載文件過大而被一次性讀取到內存中,致使內存爆滿。
相關文章
相關標籤/搜索