在Python中打开URL并获得X字节的最佳方法是什么?

我想让机器人每小时获取一个URL,但如果该网站的操作符是恶意的,他可以让他的服务器发送给我一个1 GB的文件.是否有一种很好的方法可以将下载限制为100 KB,并在该限制之后停止?

我可以想象从头开始编写自己的连接处理程序,但是我想尽可能使用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()
点赞