如果它很大......那么停止下载? 我不想下载大于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标头(如果存在)(可能不存在)。但要做到这一点,您需要下载到 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()

如果您愿意,也可以在要求获取文件之前检查长度。除了使用方法'HEAD'而不是'GET'之外,这基本上与上面相同。

您可以先检查HEAD请求中的内容长度,但要注意,不必设置此标头 - 请参阅如何在Python 2中发送HEAD HTTP请求?

如果设置了Content-Length标头

,这将有效
import urllib2          
req = urllib2.urlopen("http://example.com/file.zip")
total_size = int(req.info().getheader('Content-Length'))
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top