Python请求错误处理
我正在写一个小的Python应用程序,它使用requests库来获取和发送数据到一个网页。
现在我遇到的问题是,如果我无法连接到这个网页,代码就会停止,并显示“最大重试次数已超过”。我希望在无法连接到服务器时能够做一些事情。
这种情况可以实现吗?
以下是示例代码:
import requests
url = "http://127.0.0.1/"
req = requests.get(url)
if req.status_code == 304:
#do something
elif req.status_code == 404:
#do something else
# etc etc
# code here if server can`t be reached for whatever reason
2 个回答
1
当你在处理 ConnectionError
(连接错误)时,可能需要设置一个合适的超时时间:
url = "http://www.stackoverflow.com"
try:
req = requests.get(url, timeout=2) #2 seconds timeout
except requests.exceptions.ConnectionError as e:
# Couldn't connect
如果你想要改变重试的次数,可以查看 这个回答。
4
你想要处理一个叫做 requests.exceptions.ConnectionError
的错误,方法如下:
try:
req = requests.get(url)
except requests.exceptions.ConnectionError as e:
# Do stuff here