使用Python中的urllib和wget c功能下载文件

2024-06-11 19:50:30 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在用Python编写一个软件来从数据库下载httppdf。 有时下载停止时会显示以下消息:

retrieval incomplete: got only 3617232 out of 10689634 bytes

如何让下载在停止使用206 Partial ContentHTTP功能的地方重新启动?在

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

有什么想法吗?在

谢谢你


Tags: of功能数据库消息onlybytes软件out
1条回答
网友
1楼 · 发布于 2024-06-11 19:50:30

您可以通过发送带有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头。在

相关问题 更多 >