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()

你可能感兴趣的:(urllib_error异常处理)