Python requests 请求中的异常

总结

  • 遇到网络问题(如:DNS 查询失败、拒绝连接等)时,Requests 会抛出一个 requests.exceptions.ConnectionError 异常。
  • 如果 HTTP 请求返回了不成功的状态码, Response.raise_for_status() 会抛出一个 HTTPError 异常。
  • 若请求超时,则抛出一个 Timeout 异常。
  • 若请求超过了设定的最大重定向次数,则会抛出一个 TooManyRedirects 异常。
  • 所有Requests显式抛出的异常都继承自 requests.exceptions.RequestException 。

 

连接超时

  • 服务器在指定时间内没有应答,抛出异常 requests.exceptions.ConnectTimeout
requests.get('http://github.com', timeout=0.001)

# 抛出异常
requests.exceptions.ConnectTimeout: HTTPConnectionPool(host='github.com', port=80): Max retries exceeded with url: / (Caused by ConnectTimeoutError(<urllib3.connection.HTTPConnection object at 0x7f1b16da75f8>, 'Connection to github.com timed out. (connect timeout=0.001)'))

 

连接、读取超时

  • 若分别指定连接和读取的超时时间,服务器在指定时间没有应答,抛出异常 requests.exceptions.ConnectTimeout- timeout=([连接超时时间], [读取超时时间])
  • 连接:客户端成功连接服务器的时间
  • 读取:服务器收到请求并成功处理请求的时间
requests.get('http://github.com', timeout=(6.05, 0.01))

# 抛出异常
requests.exceptions.ReadTimeout: HTTPConnectionPool(host='github.com', port=80): Read timed out. (read timeout=0.01)

 

未知的服务器

  • 请求未知的服务器,抛出异常requests.exceptions.ConnectionError
requests.get('http://github.comasf', timeout=(6.05, 27.05))

# 抛出异常
requests.exceptions.ConnectionError: HTTPConnectionPool(host='github.comasf', port=80): Max retries exceeded with url: / (Caused by NewConnectionError('<urllib3.connection.HTTPConnection object at 0x7f75826665f8>: Failed to establish a new connection: [Errno -2] Name or service not known',))

 

代理读取超时

说明HTTP与代理服务器成功建立连接,代理服务器也成功发送请求到目标服务器,但是代理服务器读取目标服务器资源超时;
例如:假定代理可用,timeout参数代表向代理服务器的连接和读取过程的超时时间(不用关心代理服务器是否与目标服务器连接和读取成功)。

requests.get('http://github.com', timeout=(2, 0.01), proxies={"http": "192.168.10.1:800"})

# 抛出错误
requests.exceptions.ReadTimeout: HTTPConnectionPool(host='192.168.10.1:800', port=1080): Read timed out. (read timeout=0.5)

 

网络环境异常

  • 可能是断网导致,抛出异常 requests.exceptions.ConnectionError
requests.get('http://github.com', timeout=(6.05, 27.05))

# 抛出异常
requests.exceptions.ConnectionError: HTTPConnectionPool(host='github.com', port=80): Max retries exceeded with url: / (Caused by NewConnectionError('<urllib3.conne
posted @ 2022-05-22 23:09  青山原  阅读(2230)  评论(0编辑  收藏  举报