查看请求exception docs。简而言之:
如果出现网络问题(例如 DNS 故障、连接被拒绝等),Requests 将引发 ConnectionError 异常。
如果出现罕见的无效 HTTP 响应,Requests 将引发 HTTPError 异常。
如果请求超时,则会引发 Timeout 异常。
如果请求超过配置的最大重定向次数,则会引发 TooManyRedirects 异常。
Requests 明确引发的所有异常都继承自 requests.exceptions.RequestException。
为了回答您的问题,您展示的内容不会涵盖您的所有基础。您只会捕获与连接相关的错误,而不是超时的错误。
当您捕获异常时该怎么做取决于您的脚本/程序的设计。可以接受退出吗?你可以继续再试一次吗?如果错误是灾难性的并且您无法继续,那么可以,您可以通过引发 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)
正如Christian 指出的那样:
如果您希望 http 错误(例如 401 Unauthorized)引发异常,您可以调用 Response.raise_for_status。如果响应是 http 错误,这将引发 HTTPError。
一个例子:
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