在Python中打开URL并获取最多X字节的最佳方法是什么?
我想让一个机器人每小时去获取一个网址,但如果这个网站的管理员心怀不轨,他可能会让服务器给我发送一个1GB的文件。有没有什么好的办法可以限制下载,比如说限制在100KB,然后在达到这个限制后停止下载?
我可以想象从头开始写一个连接处理程序,但如果能用urllib2就更好了,只需要以某种方式指定这个限制。
谢谢!
1 个回答
7
这可能就是你想要的内容:
import urllib
def download(url, bytes = 1024):
"""Copy the contents of a file from a given URL
to a local file.
"""
webFile = urllib.urlopen(url)
localFile = open(url.split('/')[-1], 'w')
localFile.write(webFile.read(bytes))
webFile.close()
localFile.close()