|
马上注册,结交更多好友,享用更多功能^_^
您需要 登录 才可以下载或查看,没有账号?立即注册
x
本帖最后由 lzb1001 于 2022-5-6 12:49 编辑
写法1:
from urllib.request import Request, urlopen
from urllib.error import URLError, HTTPError
req = Request('http://www.fishc.com/ooxx.html')
try:
response = urlopen(req)
except HTTPError as e: # 子类HTTPError必须写在URLError的前面!
print('The sever couldn\'t fulfill the request!')
print('Error code:', e.code)
except URLError as e:
print('We failed to reach a sever!')
print('Reason:', e.reason)
#else:
# Everything is fine
得到结果如下:
The sever couldn't fulfill the request!
Error code: 404
-------------------------------------------
写法2:
from urllib.request import Request, urlopen
from urllib.error import URLError
req = Request('http://www.fishc.com/ooxx.html')
try:
response = urlopen(req)
except URLError as e:
if hasattr(e, 'reason'):
print('We failed to reach a server!')
print('Reason:', e.reason)
elif hasattr(e, 'code'):
print('The server couldn\'t fulfill the request!')
print('Error code:', e.code)
#else:
# Everything is fine
得到结果如下:
We failed to reach a server!
Reason: Not Found
------------------------
上面两个写法是完全按照小甲鱼的教材的哦……
【最新发现】
写法2其实也要像写法1那样,把HTTPError写在前面,即:
from urllib.request import Request, urlopen
from urllib.error import URLError
req = Request('http://www.fishc.com/ooxx.html')
try:
response = urlopen(req)
except URLError as e:
if hasattr(e, 'code'):
print('The server couldn\'t fulfill the request!')
print('Error code:', e.code)
elif hasattr(e, 'reason'):
print('We failed to reach a server!')
print('Reason:', e.reason)
#else:
# Everything is fine
这样得到的结果就和写法1完全一致了:
The server couldn't fulfill the request!
Error code: 404
【重要结论】
看来小甲鱼在书面教材、视频教材中的都错了,应该两种写法都要把HTTPError(写法1)或HTTPError相关内容(写法2)写在前面才行 |
|