(1)第一种写法
需要注意的是 在抛出异常的时候,HTTPError必须写在URLError之前,因为只有这样前者才能抛出异常,不然的话就会被后者拦截,提前抛出异常。
from urllib.request import Request,urlopen from urllib.error import URLError,HTTPError #请求某一个地址 req = Request(someurl) try: response = urlopen(req) except HTTPError as e: print("The server conldn\'t fulfill the request.") except URLError as e: print('We failed to reach a server.') print('reason:',e.reason) else: #everything is fine
(2)第二种写法
from urllib.request import Request,urlopen from urllib.error import URLError #请求某一个地址 req = Request("http://xx.baidu.com") try: response = urlopen(req) except URLError as e: if hasattr(e,'reason'): print("We failed to reach a server") elif hasattr(e,'code'): print("The server couldn\'t ful fill the request.") else: print("everything is fine")
hasattr判断是否拥有这个属性,如果有的话就打印,如果没有判断下一个,建议使用第二个抛异常方法。