request.get()404响应后,requests_HTTPError未被捕获

时间:2013-04-25 03:48:41

标签: 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

由于某种原因,没有抓住异常。我已经检查了API文档中的请求,但它有点渺茫。是否有人对图书馆有更多经验可以帮助我?

2 个答案:

答案 0 :(得分:10)

口译员是你的朋友:

import requests
requests.get('google.com/admin')
# MissingSchema: Invalid URL u'google.com/admin': No schema supplied

此外,requests例外:

import requests.exceptions
dir(requests.exceptions)

另请注意,如果状态不是requests,默认情况下200不会引发异常:

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

答案 1 :(得分:3)

在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

另请注意,它不是缺少的架构,而是缺少方案。