当前位置:   article > 正文

python 爬虫 网络超时与异常_httpconnectionpool(host='114.115.236.206', port=99

httpconnectionpool(host='114.115.236.206', port=9988): read timed out.

在访问一个网页时,如果该网页长时间未响应,系统就会判断该网页超时,无法打开网页。模拟代码如下:

import requests
for a in range(0,100):
    try:
        response = requests.get('http://www.baidu.com/', timeout=0.02)
        print(response.status_code)
    except Exception as e:
        print('异常'+str(e))

  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8

抛出的异常:

异常HTTPConnectionPool(host='www.baidu.com', port=80): Read timed out. (read timeout=0.02)
  • 1

识别网络异常的分类
针对网络异常信息,requests模块同样提供了三种常见的网络异常捕获异常,代码如下:

import requests
from requests.exceptions import ReadTimeout,HTTPError,RequestException
for a in range(0,100):
    try:
        response = requests.get('http://www.baidu.com/', timeout=0.02)
        print(response.status_code)
    except ReadTimeout:#超时异常
        print('time out')
    except HTTPError:#HTTP异常
        print('httperror')
    except RequestException:#请求异常
        print('reqerror')
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/你好赵伟/article/detail/172707
推荐阅读
相关标签
  

闽ICP备14008679号