我希望有一个机器人每小时获取一个URL,但如果网站的运营者是恶意的,他可能会让他的服务器发送给我一个1 GB的文件。有没有一种好的方法来限制下载,比如说限制在100KB并在达到这个限制后停止下载呢?
我可以想象自己从头开始编写连接处理程序,但如果可能的话,我还是希望使用urllib2,并以某种方式指定限制。
谢谢!
这可能是你正在寻找的内容:
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()
urllib.urlopen("url").read(1024)
。 - kyle k