【问题标题】:Download file using urllib in Python with the wget -c feature在 Python 中使用带有 wget -c 功能的 urllib 下载文件
【发布时间】:2010-01-07 15:46:42
【问题描述】:

我正在用 Python 编写一个软件来从数据库下载 HTTP PDF。 有时下载会因此消息而停止:

retrieval incomplete: got only 3617232 out of 10689634 bytes

如何使用206 Partial Content HTTP 功能要求下载在停止的地方重新开始?

我可以使用wget -c 来做到这一点,而且效果很好,但我想直接在我的 Python 软件中实现它。

有什么想法吗?

谢谢

【问题讨论】:

    标签: python http download urllib2 urllib


    【解决方案1】:

    您可以通过发送带有 Range 标头的 GET 请求部分下载:

    import urllib2
    req = urllib2.Request('http://www.python.org/')
    #
    # Here we request that bytes 18000--19000 be downloaded.
    # The range is inclusive, and starts at 0.
    #
    req.headers['Range'] = 'bytes=%s-%s' % (18000, 19000)
    f = urllib2.urlopen(req)
    # This shows you the *actual* bytes that have been downloaded.
    range=f.headers.get('Content-Range')
    print(range)
    # bytes 18000-18030/18031
    print(repr(f.read()))
    # '  </div>\n</body>\n</html>\n\n\n\n\n\n\n'
    

    请仔细检查Content-Range 以了解实际下载了哪些字节,因为您的范围可能超出范围,和/或并非所有服务器似乎都尊重Range 标头。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-06-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多