如何区分超时错误和Python中的其他`URLError`?

时间:2011-03-29 02:33:20

标签: python http urllib2

如何在Python中区分超时错误和其他URLError

修改

当我抓到URLError时,它可能是Temporary failure in name resolutiontimeout,还是其他一些错误?我怎么能告诉彼此呢?

2 个答案:

答案 0 :(得分:5)

我使用下面的选项2之类的代码......但是要获得全面的答案,请查看Michael Foord's urllib2 page

如果您使用下面的选项1或选项2,您可以通过查看e.codee.reason

在except条款中添加尽可能多的智能和分支

选项1:

from urllib2 import Request, urlopen, URLError, HTTPError
req = Request(someurl)
try:
    response = urlopen(req)
except HTTPError, e:
    print 'The server couldn\'t fulfill the request.'
    print 'Error code: ', e.code
except URLError, e:
    print 'We failed to reach a server.'
    print 'Reason: ', e.reason
else:
    # everything is fine

选项2:

from urllib import urlencode
from urllib2 import Request
# insert other code here...
    error = False
    error_code = ""
    try:
        if method.upper()=="GET":
            response = urlopen(req)
        elif method.upper()=="POST":
            response = urlopen(req,data)
    except IOError, e:
        if hasattr(e, 'reason'):
            #print 'We failed to reach a server.'
            #print 'Reason: ', e.reason
            error = True
            error_code = e.reason
        elif hasattr(e, 'code'):
            #print 'The server couldn\'t fulfill the request.'
            #print 'Error code: ', e.code
            error = True
            error_code = e.code
    else:
        # info is dictionary of server parameters, such as 'content-type', etc...
        info = response.info().dict
        page = response.read()

答案 1 :(得分:0)

我使用以下代码来区分超时错误和其他URLError

except URLError, e:
    if e.reason.message == 'timed out':
        # handle timed out exception
    else:
        # other URLError