通过urllib发送请求的时候,可能会发送失败,可以用try-except捕获异常,
异常有两类,urlerror和httperror
httperror的原因是url中的参数错误,urlerror是因为url的主机错误
import urllib.request
import urllib.error
url = 'https://blog.csdn.net/weixin_45735355/article/details/1225749201'
# url = 'http://www.doudan111.com'
headers = {
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/97.0.4692.99 Safari/537.36'
}
try:
request = urllib.request.Request(url = url, headers = headers)
response = urllib.request.urlopen(request)
content = response.read().decode('utf-8')
print(content)
except urllib.error.HTTPError:
print('httperror系统正在升级。。。')
except urllib.error.URLError:
print('urlerror系统正在升级。。。')