异常处理 URLError
from urllib import request,error
try:
response=request.urlopen('http://cuiqingcal.com/index.html')
except error.URLError as e:
print(e.reason)
URLError和HTTPError异常
from urllib import request,error
try:
response=request.urlopen('https://httpbin.org/post')
except error.HTTPError as e:
print(e.reason,e.code,e.headers,sep='\n')
except error.URLError as e:
print(e.reason)
else:
print('Request Successfully')
输出
METHOD NOT ALLOWED
405
Access-Control-Allow-Credentials: true
Access-Control-Allow-Origin: *
Allow: POST, OPTIONS
Content-Type: text/html
Date: Mon, 13 May 2019 06:15:41 GMT
Referrer-Policy: no-referrer-when-downgrade
Server: nginx
X-Content-Type-Options: nosniff
X-Frame-Options: DENY
X-XSS-Protection: 1; mode=block
Content-Length: 178
Connection: Close
验证异常原因
import socket
import urllib.request
import urllib.error
try:
response=urllib.request.urlopen('http://www.baid.com',timeout=0.01)
except urllib.error.URLError as e:
print(e.reason)
if isinstance(e.reason,socket.timeout):
print('TIME OUT')
输出
timed out
TIME OUT