【python2.7】urllib2异常处理之urllib2.URLError的使用

参考官方文档:https://docs.python.org/2/howto/urllib2.html#urllib-howto

  • urlopen无法处理服务器返回的response时会抛出异常URLError
  • HTTPError是URLError的子类
>>> from urllib2 import URLError
>>> req = urllib2.Request('http://www.pretend_server.org')
>>> try: urllib2.urlopen(req)
except URLError as e:
    print e.reason

[Errno 11004] getaddrinfo failed
>>> req = urllib2.Request('http://www.python.org/fish.html')
>>> try:
    urllib2.urlopen(req)
except urllib2.HTTPError as e:
    print e.code
    print e.read(100)
    print e.reason

    
404


你可能感兴趣的:(【python2.7】urllib2异常处理之urllib2.URLError的使用)