Cof*_*ing 2 python error-handling try-catch python-requests
我的请求库有点问题.
比方说,我在Python中有这样的声明:
try:
request = requests.get('google.com/admin') #Should return 404
except requests.HTTPError, e:
print 'HTTP ERROR %s occured' % e.code
Run Code Online (Sandbox Code Playgroud)
由于某种原因,异常没有被捕获.我已经检查了API文档中的请求,但它有点渺茫.是否有人对图书馆有更多经验可以帮助我?
gat*_*tto 11
口译员是你的朋友:
import requests
requests.get('google.com/admin')
# MissingSchema: Invalid URL u'google.com/admin': No schema supplied
Run Code Online (Sandbox Code Playgroud)
另外,requests例外:
import requests.exceptions
dir(requests.exceptions)
Run Code Online (Sandbox Code Playgroud)
另请注意,requests如果status不是,则默认情况下不会引发异常200:
In [9]: requests.get('https://google.com/admin')
Out[9]: <Response [503]>
Run Code Online (Sandbox Code Playgroud)
有raise_for_status()方法可以做到:
In [10]: resp = requests.get('https://google.com/admin')
In [11]: resp
Out[11]: <Response [503]>
In [12]: resp.raise_for_status()
...
HTTPError: 503 Server Error: Service Unavailable
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
14783 次 |
| 最近记录: |