Python3网络爬虫——(4)urllib.error异常处理

异常处理

1、使用URLError进行异常处理

# -*- coding: UTF-8 -*-
from urllib import request
from urllib import error
if __name__ == "__main__":
     url = 'https://blog.csdn.net/asialee_bir'  #错误链接
     try:
        response=request.urlopen(url)
        file=response.read().decode('utf-8')
        print(file)
     except  error.URLError as e:
        print(e.code)
        print(e.reason)

异常结果:(403错误表示禁止访问)

 

 

2、使用HTTPError进行异常处理

# -*- coding: UTF-8 -*-
from urllib import request
from urllib import error
if __name__ == "__main__":
    url = 'https://blog.csdn.net/asialee_bir'  #错误链接
    try:
        response=request.urlopen(url)
        file=response.read().decode('utf-8')
        print(file)
    except error.HTTPError as e:
        print(e.code)    #返回状态码
        print(e.reason)

异常结果:(403错误表示禁止访问)

 

注意:URLError是HTTPError的父类

 

3、URLError和TTPError混合使用

# -*- coding: UTF-8 -*-
from urllib import request
from urllib import error
if __name__ == "__main__":
    url = 'https://blog.baidusss.net'  #不存在的链接
    try:
        response=request.urlopen(url)
        file=response.read().decode('utf-8')
        print(file)
    except error.URLError as e:
        if hasattr(e,'code'):   #使用hasattr()判断是否有这些属性
             print('HTTPError')
             print(e.code)
        if hasattr(e,'reason'):
             print('URLError')
             print(e.reason)

 

 

 

 

 

 

 

 

全部评论

相关推荐

CARLJOSEPH...:宝宝你戾气太大了
点赞 评论 收藏
分享
见见123:简历没有啥问题,是这个社会有问题。因为你刚毕业,没有工作经历,现在企业都不要没有工作经历的。社会病了。
点赞 评论 收藏
分享
陆续:不可思议 竟然没那就话 那就我来吧 :你是我在牛客见到的最美的女孩
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务