看看请求异常文档 https://requests.readthedocs.io/en/latest/user/quickstart/#errors-and-exceptions。简而言之:
如果出现网络问题(例如 DNS 故障、拒绝连接等),请求将引发ConnectionError
例外。
如果出现罕见的无效 HTTP 响应,请求将引发HTTPError
例外。
如果请求超时,Timeout
引发异常。
如果请求超过配置的最大重定向次数,TooManyRedirects
引发异常。
Requests 显式引发的所有异常都继承自requests.exceptions.RequestException
.
为了回答你的问题,你所展示的内容将not覆盖你所有的基地。您只会捕获与连接相关的错误,而不会捕获超时的错误。
捕获异常时要做什么实际上取决于脚本/程序的设计。退出是否可以接受?你能继续再试一次吗?如果错误是灾难性的并且您无法继续,那么是的,您可以通过引发来中止您的程序系统退出 https://docs.python.org/3/library/exceptions.html#SystemExit(打印错误和调用的好方法sys.exit
).
您可以捕获基类异常,它将处理所有情况:
try:
r = requests.get(url, params={'s': thing})
except requests.exceptions.RequestException as e: # This is the correct syntax
raise SystemExit(e)
或者你可以单独抓住它们并做不同的事情。
try:
r = requests.get(url, params={'s': thing})
except requests.exceptions.Timeout:
# Maybe set up for a retry, or continue in a retry loop
except requests.exceptions.TooManyRedirects:
# Tell the user their URL was bad and try a different one
except requests.exceptions.RequestException as e:
# catastrophic error. bail.
raise SystemExit(e)
As 基督教 https://stackoverflow.com/users/456550/christian-long指出:
如果您希望 http 错误(例如 401 Unauthorized)引发异常,您可以调用Response.raise_for_status https://requests.readthedocs.io/en/latest/api/#requests.Response.raise_for_status。这将提高一个HTTPError
,如果响应是 http 错误。
一个例子:
try:
r = requests.get('http://www.google.com/nothere')
r.raise_for_status()
except requests.exceptions.HTTPError as err:
raise SystemExit(err)
将打印:
404 Client Error: Not Found for url: http://www.google.com/nothere