Python 请求异常处理

68 投票
5 回答
140556 浏览
提问于 2025-04-17 11:53

如何使用Python的requests库处理异常?比如,怎么检查电脑是否连接到互联网?

当我尝试这样做时:

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

它给我报错,提示名称ConnectionError未定义。

5 个回答

11

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

根据文档,我总结了以下几点:

  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()会抛出这个异常。

    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的异常。

你可以通过设置一个超时时间,让Requests在等待响应时,超过一定秒数就停止等待,这个设置叫做timeout。

    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
  1. 所有Requests明确抛出的异常都继承自requests.exceptions.RequestException。所以一个基本的异常处理器可以像这样,

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

原来的Python v2文档链接已经失效,现在指向新的文档。

92

假设你已经使用了 import requests,那么你需要用到 requests.ConnectionErrorConnectionError 是一个由 requests 定义的错误类型。你可以在这里查看 API 文档

所以代码应该是:

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

原来的 Python v2 API 文档链接已经失效。

撰写回答