如何用python库请求处理异常? 例如如何检查电脑是否连接到互联网?Python请求异常处理
当我尝试
try:
requests.get('http://www.google.com')
except ConnectionError:
# handle the exception
它给我的错误名称ConnectionError
没有定义
如何用python库请求处理异常? 例如如何检查电脑是否连接到互联网?Python请求异常处理
当我尝试
try:
requests.get('http://www.google.com')
except ConnectionError:
# handle the exception
它给我的错误名称ConnectionError
没有定义
假设你做import requests
,你要requests.ConnectionError
。 ConnectionError
是由requests
定义的例外。请点击此处查看API documentation。
为了清楚,是
except requests.ConnectionError:
不
import requests.ConnectionError
您还可以赶上一般例外(虽然这是不建议使用),
except Exception:
实际上,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
请附上你想处理异常的回溯。 – AdamKG 2012-01-29 16:47:44