处理HTTP错误和URL错误

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

urlopen返回的response(或者HTTP错误实例)有两个有用的方法:infogeturl

geturl–它返回被获取网页的真正的url。这是很有用的,因为urlopen(或使用的opener对象)也许会伴随一个重定向。获取的网页url也许和要求的网页url不一样。

info–它返回一个像字典的对象来描述获取的网页,尤其是服务器发送的头。它现在一般是httplib.HTTPMessage的一个实例。

posted @ 2013-09-13 01:06  boole  阅读(846)  评论(0)    收藏  举报