2011-03-29 35 views

回答

5

我使用如下代码选项2,下面......但对于一个全面的答案,看看Michael Foord's urllib2 page

如果您使用选项1或以下的选项2,您可以添加尽可能多的情报和分支,只要你喜欢在除了通过查看e.codee.reason

选项条款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() 
+0

请你告诉我哪里可以看一下对'timeout'相应的'reason'代码? – satoru 2011-03-29 03:37:14

+0

我假设你正在谈论HTTP超时,这是HTTP错误e.code = 408 – 2011-03-29 03:40:39

+0

也许我应该尝试e.reason =='超时'。我读了'URLError'的源代码,它的'__str__'就像'%self.reason'一样,在我的回溯中,我可以看到''。 – satoru 2011-03-29 03:45:28

0

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

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