这篇博客主要是记录Python访问互联网时处理异常的两种方法:
第一种方法
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 is could\'t fulfill the request.')
print('Error code:,e.code')
except URLError as e:
print('We failed to reach a serve.')
print('Reason:',e.reason)
第二种方法
from urllib.request import Request,urlopen
from urllib.error import URLError
req=Request(someurl)
try:
response=urlopen(req)
except URLError as e:
if hasattr(e,'reason'):
print("We failed to reach a serve")
elif hasattr(e,'code'):
print("The serve couldn\'t fulfill the request.")
print("Error code:",e.code)
推荐使用第二种方法。