Python3网络爬虫教程3——urllib.error的使用

版权声明:本文章为沐言-BigTree原创,转载复制请标明出处 https://blog.csdn.net/u011318077/article/details/86510874

上接:Python3网络爬虫教程2——urlopen的返回对象
https://blog.csdn.net/u011318077/article/details/86510682

2.5. urllib.error

  • URLError产生的原因
    • 没网
    • 服务器连接失败
    • 是OSError的子类
    • 看案例43_7
  • HTTPError是URLError的一个子类
    • 看案例43_8
  • 两者区别:
    • HTTPError是对应的HTTP请求的返回码错误
    • 如果返回错误码是400以上的则返回HTTPError
    • URLError对应的一般是网络出现错误,包括url问题
    • 关系区别:OSError-URLError-HTTPError
  • 爬虫执行以下代码时候,都放在try模块下
    try:
    req = request.Request(url)
    rsp = request.urlopen(req)

43-7

# URLError的使用

from urllib import request, error

if __name__ == '__main__':

    # 输入一个错误网址
    url = 'http://www.sipo.gov.cn/www'
    # 下面网址会自动跳转
    # url = 'http://www.22222fdadfafddddddu.com'

    try:
        req = request.Request(url)
        rsp = request.urlopen(req)
        html = rsp.read().decode()
        print(html)

    except error.URLError as e:
        print("URLError: {0}".format(e.reason))
        print("URLError: {0}".format(e))

    except Exception as e:
        print(e)

    # 错误并没有执行,执try时候网页自动跳转了,跳转到了一个新网页
    # 为了显示错误的结果:
    # 方法1:可以把网断掉,然后再次执行,结果如下
    # URLError: [Errno 11001] getaddrinfo failed
    # URLError: <urlopen error [Errno 11001] getaddrinfo failed>
    # 方法2:将url替换为一个政府的错误网址,结果如下
    # HTTPError: Not Found
    # HTTPError: HTTP Error 404: Not Found

43-8

# HTTPError的使用

from urllib import request, error

if __name__ == '__main__':

    # 输入一个错误网址
    url = 'http://www.sipo.gov.cn/www'

    try:
        req = request.Request(url)
        rsp = request.urlopen(req)
        html = rsp.read().decode()
        print(html)

    except error.HTTPError as e:
        print("HTTPError: {0}".format(e.reason))
        print("HTTPError: {0}".format(e))


    except error.URLError as e:
        print("URLError: {0}".format(e.reason))
        print("URLError: {0}".format(e))

    except Exception as e:
        print(e)

下接:
Python3网络爬虫教程4——UserAgent的使用(用户伪装)(附常用的UserAgent值清单)
https://blog.csdn.net/u011318077/article/details/86508095

猜你喜欢

转载自blog.csdn.net/u011318077/article/details/86510874