python - 使用 wget -c 功能在 Python 中使用 urllib 下载文件

标签 python http download urllib2 urllib

我正在用 Python 编写软件以从数据库下载 HTTP PDF。 有时下载会停止并显示此消息:

retrieval incomplete: got only 3617232 out of 10689634 bytes

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

我可以使用 wget -c 来完成它并且它工作得很好,但我想直接在我的 Python 软件中实现它。

有什么想法吗?

谢谢

最佳答案

您可以通过发送带有 Range header 的 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 header 。

关于python - 使用 wget -c 功能在 Python 中使用 urllib 下载文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2021519/

相关文章:

python - 尝试在pycharm中导入flask管理模块

javascript - 从 javascript 执行 python 脚本

Python - 根据提供的模式生成文件名

python - 如何使用 pythonw 运行 Selenium Webdriver?

java - 如何在 HTTP 之上设计 Java 服务器和 Java worker 之间的协议(protocol)?

java代码从服务器下载图像到客户端

http - golang : core net/http package import errors

http - 将 Flume JSONHandler 主体作为 JSONObject 发送

c - 如何使用 C 套接字编程下载文件

php - fread 的下载速度比 readfile 慢很多