參考官方文檔:https://docs.python.org/2/howto/urllib2.html#urllib-howto
- urlopen無法處理服務(wù)器返回的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
<!doctype html>
<!--[if lt IE 7]> <html class="no-js ie6 lt-ie7 lt-ie8 lt-ie9"> <![endif]-->
<!-
OK