Python请求异常处理

时间:2012-01-29 16:46:55

标签: python exception http-request python-requests

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

当我尝试

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

它给我错误名称ConnectionError未定义

5 个答案:

答案 0 :(得分:64)

假设您执行了import requests,则需要requests.ConnectionErrorConnectionErrorrequests定义的例外情况。请参阅此处的API documentation

因此代码应为:

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

答案 1 :(得分:6)

为清楚起见,即

except requests.ConnectionError:

不是

import requests.ConnectionError

您还可以使用

捕获一般异常(尽管不建议这样做)
except Exception:

答案 2 :(得分:4)

实际上,除了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

答案 3 :(得分:1)

使用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")

答案 4 :(得分:0)

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

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

    try:
       requests.get('http://www.google.com')
    except requests.ConnectionError:
       # handle ConnectionError the exception
    
  2. 在罕见的无效HTTP响应事件中,请求将引发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. 如果请求超时,则会引发Timeout异常。

    您可以让请求在给定的秒数后停止等待响应,并且超时arg。

    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显式引发的所有异常都继承自request.exceptions.RequestException。因此,基本处理程序可能看起来像

    try:
       r = requests.get(url)
    except requests.exceptions.RequestException as e:
       # handle all the errors here