【问题标题】:Python requests start downlaoding a file from a checkpointPython 请求开始从检查点下载文件
【发布时间】:2018-12-02 08:07:29
【问题描述】:

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

我把代码贴在下面

res = requests.get(link)
playfile = open(file_name, 'wb')

for chunk in res.iter_content(100000):
    playfile.write(chunk)

【问题讨论】:

  • 这个文件有多大?不能一口气下载吗?
  • 视情况而定,有时它是一个大约 1Gb 的视频文件,有时是一个重量约为 0.5Mb 的图片。我使用其他库来废弃发布这些内容的网站,我提供的片段只是下载文件,而不是找到链接。除此之外,我真的很想解决这个问题

标签: python python-3.x http python-requests


【解决方案1】:

可以通过Range 继续从检查点下载。其实你的问题类似于How to `pause`, and `resume` download work?

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

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)

【讨论】:

    猜你喜欢
    • 2014-07-05
    • 2020-08-20
    • 2013-03-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-08-06
    • 2021-08-21
    • 1970-01-01
    相关资源
    最近更新 更多