我在requests库上遇到了一点小问题。
例如,我在Python中有这样一条语句:
try:
request = requests.get('google.com/admin') #Should return 404
except requests.HTTPError, e:
print 'HTTP ERROR %s occured' % e.code由于某些原因,该异常未被捕获。我已经检查了API文档中的请求,但它有点小。有没有对图书馆有更多经验的人可以帮我解决这个问题?
发布于 2013-04-25 12:13:14
解释器是你的朋友:
import requests
requests.get('google.com/admin')
# MissingSchema: Invalid URL u'google.com/admin': No schema supplied另外,requests异常:
import requests.exceptions
dir(requests.exceptions)还要注意,默认情况下,如果状态不是200,requests不会引发异常
In [9]: requests.get('https://google.com/admin')
Out[9]: <Response [503]>有一个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发布于 2013-08-02 12:08:14
在python 2.7.5中运行代码:
import requests
try:
response = requests.get('google.com/admin') #Should return 404
except requests.HTTPError, e:
print 'HTTP ERROR %s occured' % e.code
print e结果如下:
File "C:\Python27\lib\site-packages\requests\models.py", line 291, in prepare_url raise MissingSchema("Invalid URL %r: No schema supplied" % url) requests.exceptions.MissingSchema: Invalid URL u'google.com/admin': No schema supplied
要让您的代码拾取此异常,您需要添加:
except (requests.exceptions.MissingSchema) as e:
print 'Missing schema occured. status'
print e另请注意,它不是一个缺失的模式,而是一个缺失的方案。
https://stackoverflow.com/questions/16206062
复制相似问题