如果文件很大,那就停止下载吧?我不想下载超过12MB的文件。
request = urllib2.Request(ep_url)
request.add_header('User-Agent',random.choice(agents))
thefile = urllib2.urlopen(request).read()
不需要像bobince那样放弃使用httplib。你可以直接使用urllib完成所有操作:
>>> import urllib2
>>> f = urllib2.urlopen("http://dalkescientific.com")
>>> f.headers.items()
[('content-length', '7535'), ('accept-ranges', 'bytes'), ('server', 'Apache/2.2.14'),
('last-modified', 'Sun, 09 Mar 2008 00:27:43 GMT'), ('connection', 'close'),
('etag', '"19fa87-1d6f-447f627da7dc0"'), ('date', 'Wed, 28 Oct 2009 19:59:10 GMT'),
('content-type', 'text/html')]
>>> f.headers["Content-Length"]
'7535'
>>>
如果您使用httplib,则可能需要实现重定向处理、代理支持以及urllib2为您提供的其他好处。
maxlength= 12*1024*1024
thefile= urllib2.urlopen(request).read(maxlength+1)
if len(thefile)==maxlength+1:
raise ThrowToysOutOfPramException()
但是,当然,您仍然读取了12MB的不需要的数据。如果您想最小化这种情况发生的风险,可以检查HTTP Content-Length头(如果存在)。但是,要做到这一点,您需要降级到更通用的urllib而非httplib。
u= urlparse.urlparse(ep_url)
cn= httplib.HTTPConnection(u.netloc)
cn.request('GET', u.path, headers= {'User-Agent': ua})
r= cn.getresponse()
try:
l= int(r.getheader('Content-Length', '0'))
except ValueError:
l= 0
if l>maxlength:
raise IAmCrossException()
thefile= r.read(maxlength+1)
if len(thefile)==maxlength+1:
raise IAmStillCrossException()
'HEAD'
方法而不是'GET'
方法。如果设置了Content-Length头,则此方法将起作用。
import urllib2
req = urllib2.urlopen("http://example.com/file.zip")
total_size = int(req.info().getheader('Content-Length'))
.strip()
:1. getheader()
已经返回了去除空格的版本 2. int()
不关心前导/尾随空格。 - jfsint(info().getheader())
没有意义:从int
引发的ValueError
比从req.headers
引发的KeyError
不太合适(注意:req.info() is req.headers
)。 - jfs你可以先在 HEAD 请求中检查 content-length,但要注意,这个头部不一定被设置 - 参见 如何在 Python 2 中发送 HEAD HTTP 请求?