tux*_*tux 34 python exception http-request python-requests
如何使用python库请求处理异常?例如,如何检查PC是否连接到互联网?
当我尝试
try:
requests.get('http://www.google.com')
except ConnectionError:
# handle the exception
Run Code Online (Sandbox Code Playgroud)
它给我的错误名称ConnectionError没有定义
kin*_*all 68
假设你做了import requests,你想要requests.ConnectionError.ConnectionError是由...定义的例外requests.请在此处查看API文档.
因此代码应该是:
try:
requests.get('http://www.google.com')
except requests.ConnectionError:
# handle the exception
Run Code Online (Sandbox Code Playgroud)
abh*_*ana 27
根据文档,我添加了以下几点:-
如果出现网络问题(拒绝连接,例如互联网问题),Requests 将引发 ConnectionError 异常。
try:
requests.get('http://www.google.com')
except requests.ConnectionError:
# handle ConnectionError the exception
Run Code Online (Sandbox Code Playgroud)如果出现罕见的无效 HTTP 响应,Requests 将引发 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
Run Code Online (Sandbox Code Playgroud)如果请求超时,则会引发 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
Run Code Online (Sandbox Code Playgroud)Requests 显式引发的所有异常都继承自 requests.exceptions.RequestException。所以基本处理程序看起来像,
try:
r = requests.get(url)
except requests.exceptions.RequestException as e:
# handle all the errors here
Run Code Online (Sandbox Code Playgroud)为清楚起见,那就是
except requests.ConnectionError:
Run Code Online (Sandbox Code Playgroud)
不
import requests.ConnectionError
Run Code Online (Sandbox Code Playgroud)
您还可以捕获一般异常(尽管不建议这样做)
except Exception:
Run Code Online (Sandbox Code Playgroud)
使用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")
Run Code Online (Sandbox Code Playgroud)
实际上,除了之外,还会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
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
45866 次 |
| 最近记录: |