您的位置:首页 > 编程语言 > Python开发

Python零基础入门二十五之访问互联网异常的处理方法

2017-01-21 14:13 836 查看
这篇博客主要是记录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)


推荐使用第二种方法。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  python