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

Python爬虫之urllib库里面的处理错误

2018-01-15 23:00 253 查看
import urllib.request
# 这是一个不存在的页面,爬出这个页面的时候,就会出错,我们要做的就是捕捉这个错误
url = 'http://blog.csdn.net/u013630017/article/details/519211445'
headers = {
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/63.0.3239.84 Safari/537.36'
}
#正常的请求
request = urllib.request.Request(url=url,headers=headers)
# response = urllib.request.urlopen(request)
#
# print(response.read().decode('utf-8'))
# 捕获异常的方法!!和 HTTPError 的错误
# 根据不同的错误,会进行精确捕捉
try:
response = urllib.request.urlopen(request)
print(response.read().decode('utf-8'))
except urllib.error.HTTPError as e:
print(100)
print(e.code)
print(e.reason)
except urllib.error.URLError as e:
print(200)
print(e)
except Exception as e:
print(300)
print(e)
# print(response.read().decode('utf-8'))
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  urllib 爬虫 异常 python