urllib / urllib2返回的错误代码和实际页面 [英] Error codes returned by urllib/urllib2 and the actual page

查看:174
本文介绍了urllib / urllib2返回的错误代码和实际页面的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

urlib / urllib2的正常行为是如果在响应的头部发送错误代码(即404),则引发异常。



如何根据不同的错误寻找特定的错误(40x或50x),做不同的事情。另外,您如何读取HTML / JSON等返回的实际数据(数据通常具有与HTML错误代码不同的错误详细信息)

解决方案

urllib2引发了 HTTPError 发生HTTP错误时。您可以使用代码获取到异常对象的响应代码。您可以使用 read()获取答复数据:

 
>>> req = urllib2.Request('http://www.python.org/fish.html')
>>> try:
>>> urllib2.urlopen(req)
>>>除了urllib2.HTTPError,e:
>>> print e.code
>>> print e.read()
>>>
404
< actual数据响应将在这里>


the normal behavior of urllib/urllib2 is if an error code is sent in the header of the response (i.e 404) an Exception is raised.

How do you look for specific errors i.e (40x, or 50x) based on the different errors, do different things. Also, how do you read the actual data being returned HTML/JSON etc (The data usually has error details which is different to the HTML error code)

解决方案

urllib2 raises a HTTPError when HTTP errors happen. You can get to the response code using code on the exception object. You can get the response data using read():

>>> req = urllib2.Request('http://www.python.org/fish.html')
>>> try:
>>>     urllib2.urlopen(req)
>>> except urllib2.HTTPError, e:
>>>     print e.code
>>>     print e.read()
>>>
404
<actual data response will be here>

这篇关于urllib / urllib2返回的错误代码和实际页面的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆