python爬虫学习3_urlLib异常处理

版权声明:随意了,开心就好。反正是给大家分享的笔记 https://blog.csdn.net/u011486491/article/details/82973364

python爬虫学习3_urlLib异常处理

urllib.error有两个方法,URLError和HTTPError。

HTTPError就是我们常用的服务器返回的错误码。它是URLError的一个子类。

常用的代码结构:

通过hasattr判断是否有对应属性,然后再打印。

# -*- coding: UTF-8 -*-
from urllib import request
from urllib import error
​
if __name__ == "__main__":
    # 一个不存在的连接
    url = "http://www.douyu.com/Jack_Cui.html"
    req = request.Request(url)
    try:
        responese = request.urlopen(req)
    except error.URLError as e:
        if hasattr(e, 'code'):
            print("HTTPError")
            print(e.code)
        elif hasattr(e, 'reason'):
            print("URLError")
            print(e.reason)
扫描二维码关注公众号,回复: 4734214 查看本文章

猜你喜欢

转载自blog.csdn.net/u011486491/article/details/82973364