58

如何处理 python 库请求的异常?例如如何检查 PC 是否连接到互联网?

当我尝试

try:
    requests.get('http://www.google.com')
except ConnectionError:
    # handle the exception

它给了我错误名称ConnectionError未定义

4

5 回答 5

84

假设你做到了import requests,你想要requests.ConnectionErrorConnectionError是由 定义的异常requests。请参阅此处的API 文档

因此代码应该是:

try:
   requests.get('http://www.google.com')
except requests.ConnectionError:
   # handle the exception
于 2012-01-29T16:52:23.390 回答
28

根据文档,我添加了以下几点:-

  1. 如果出现网络问题(拒绝连接,例如互联网问题),Requests 将引发 ConnectionError 异常。

    try:
       requests.get('http://www.google.com')
    except requests.ConnectionError:
       # handle ConnectionError the exception
    
  2. 如果出现罕见的无效 HTTP 响应,Requests 将引发 HTTPError 异常。如果 HTTP 请求返回不成功的状态代码,Response.raise_for_status() 将引发 HTTPError。

    try:
       r = requests.get('http://www.google.com/nowhere')
       r.raise_for_status()
    except requests.exceptions.HTTPError as err:
       #handle the HTTPError request here
    
  3. 如果请求超时,则会引发超时异常。

    您可以使用超时参数告诉请求在给定的秒数后停止等待响应。

    requests.get('https://github.com/', timeout=0.001)
    # timeout is not a time limit on the entire response download; rather, 
    # an exception is raised if the server has not issued a response for
    # timeout seconds
    
  4. Requests 显式引发的所有异常都继承自 requests.exceptions.RequestException。所以一个基础处理程序看起来像,

    try:
       r = requests.get(url)
    except requests.exceptions.RequestException as e:
       # handle all the errors here
    
于 2019-07-28T09:47:27.217 回答
9

实际上,requests.get()可以生成的异常远不止ConnectionError. 以下是我在生产中看到的一些:

from requests import ReadTimeout, ConnectTimeout, HTTPError, Timeout, ConnectionError

try:
    r = requests.get(url, timeout=6.0)
except (ConnectTimeout, HTTPError, ReadTimeout, Timeout, ConnectionError):
    continue
于 2017-09-06T09:57:41.880 回答
8

为清楚起见,即

except requests.ConnectionError:

不是

import requests.ConnectionError

 

您还可以使用以下方法捕获一般异常(尽管不建议这样做)

except Exception:
于 2015-02-22T10:50:29.980 回答
7

使用 包含请求模块import requests

实现异常处理总是好的。它不仅有助于避免脚本意外退出,还有助于记录错误和信息通知。当使用 Python 请求时,我更喜欢捕获这样的异常:

try:
    res = requests.get(adress,timeout=30)
except requests.ConnectionError as e:
    print("OOPS!! Connection Error. Make sure you are connected to Internet. Technical Details given below.\n")
    print(str(e))            
    continue
except requests.Timeout as e:
    print("OOPS!! Timeout Error")
    print(str(e))
    continue
except requests.RequestException as e:
    print("OOPS!! General Error")
    print(str(e))
    continue
except KeyboardInterrupt:
    print("Someone closed the program")
于 2018-05-23T20:19:50.793 回答