urllib_error异常处理

# urllib.error : 在发起请求的过程中,可能会因为各种情况
# 导致请求出现异常,因而导致代码崩溃,所以我们悬疑处理这些异常的请求


from urllib import error,request

# error.URLError

def check_urlerror():
    '''
    1.没有网络
    2.服务器连接失败
    3.找不到指定服务器
    :return:
    '''
    url = 'http://www.baiduxxx.com/'
    try:
        response = request.urlopen(url)
        print(response.status)

    except error.URLError as err:
        #[Errno-2] Name or service not known(未知服务器)
        #timed out:请求超时
        #[Errno-3]Temporary failure in name resolution (没网)
        print(err.reason)
check_urlerror()

def check_httperror():
    """
    处理认证或则请求失败的错误
    例如:出现404表示页面未找到等
    code:返回的HTTP状态码
    reason:返回的错误原因
    headers:返回的请求头
    :return:
    """
    req_url = 'https://www.qidian.com/all/nsacnscn.htm'

    try:
        response = request.urlopen(url=req_url)
        print(response.status)
    except error.HTTPError as err:
        """
        Not Found (reason)
        404 (code)
        Server: nginx (headers)
        Date: Mon, 19 Nov 2018 13:36:11 GMT
        Content-Type: text/html; charset=utf-8
        Content-Length: 15616
        Connection: close
        """
        print('===', err.reason,err.code,err.headers)

check_httperror()
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容