Python请求开始从检查点下载文件



我想下载一个带有Python请求库的文件。问题是,当我失去与网络的连接时,必须再次下载该文件。问题是:我如何让程序知道他最后一次完成的地方,并从这一点开始下载文件?

我把代码粘贴到下面

res = requests.get(link)
playfile = open(file_name, 'wb')
for chunk in res.iter_content(100000):
playfile.write(chunk)

可以通过Range从检查点继续下载。实际上,你的问题类似于如何"暂停"one_answers"恢复"下载工作?。

这是一个展示其工作原理的示例。

import requests
def DownloadFile(url):
local_filename = url.split('/')[-1]
with requests.Session() as s:
r = s.get(url,headers={"Range": "bytes=0-999"})
with open(local_filename, 'wb') as fd:
fd.write(r.content)
r2 = s.get(url,headers={"Range": "bytes=1000-"})
with open(local_filename, 'ab') as fd:
fd.write(r2.content)
return 
url = "https://upload.wikimedia.org/wikipedia/commons/thumb/6/63/BBC_Radio_logo.svg/210px-BBC_Radio_logo.svg.png" 
DownloadFile(url)

现在,我们可以建立一个函数,从检查点开始下载文件。

import requests
import os
def Continue_(url):
local_filename = url.split('/')[-1]
with requests.Session() as s:
if os.path.exists(local_filename):
position = os.stat(local_filename).st_size
else:
position = 0
r2 = s.get(url,headers={"Range": "bytes={}-".format(position)})
with open(local_filename, 'ab+') as fd:
for c in r2.iter_content():
fd.write(c)
url = "https://upload.wikimedia.org/wikipedia/commons/thumb/6/63/BBC_Radio_logo.svg/210px-BBC_Radio_logo.svg.png" 
def DownloadFile(url):
local_filename = url.split('/')[-1]
with requests.Session() as s:
r = s.get(url,headers={"Range": "bytes=0-999"})
with open(local_filename, 'wb') as fd:
fd.write(r.content)
DownloadFile(url)
Continue_(url)

最新更新