TIM*_*MEX 9 python file download urllib2
如果它很大......那么停止下载?我不想下载大于12MB的文件.
request = urllib2.Request(ep_url)
request.add_header('User-Agent',random.choice(agents))
thefile = urllib2.urlopen(request).read()
Run Code Online (Sandbox Code Playgroud)
And*_*lke 20
没有必要像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'
>>>
Run Code Online (Sandbox Code Playgroud)
如果你使用httplib,那么你可能必须实现重定向处理,代理支持以及urllib2为你做的其他好事.
你可以说:
maxlength= 12*1024*1024
thefile= urllib2.urlopen(request).read(maxlength+1)
if len(thefile)==maxlength+1:
raise ThrowToysOutOfPramException()
Run Code Online (Sandbox Code Playgroud)
但当然你还是读了12MB不需要的数据.如果要最大限度地降低发生这种情况的风险,可以检查HTTP Content-Length标头(如果存在)(可能不存在).但要做到这一点,你需要下载到httplib而不是更通用的urllib.
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()
Run Code Online (Sandbox Code Playgroud)
如果您愿意,也可以在要求获取文件之前检查长度.除了使用方法'HEAD'代替之外,这基本上与上面相同'GET'.