python urllib2 库简单 http_error_default 错误处理程序

标签 python urllib2

这就是我的类(class)的样子:

class ExtHTTPErrorProcessor (urllib2.BaseHandler):

def http_error_default(self, req, fp, code, msg, hdrs):
    print code
    return res
...
...
opener = urllib2.build_opener(ExtHTTPErrorProcessor())
urllib2.install_opener(opener)
urllib2.urlopen(request, data)

它所做的只是处理所有错误代码。我完全遵循文档中的格式:http://docs.python.org/library/urllib2.html#urllib2.BaseHandler.http_error_default 当错误代码 400 出现时,它根本不调用我的 http_error_default,而是调用 urllib2 内部的。 文件“/usr/local/lib/python2.7/urllib2.py”,第 521 行,位于 http_error_default 引发HTTPError(req.get_full_url(),代码,msg,hdrs,fp) urllib2.HTTPError:HTTP 错误 400:错误请求

我尝试添加方法http_error_400,然后该方法将被调用,但我确实需要http_error_default。我真的需要一个默认的。

最佳答案

根据this vague old thread您必须在“Fancy”URL Opener 中指定显式处理程序...我坚持使用 my simple working solution 。只需添加一个 try ... except block 即可。

关于python urllib2 库简单 http_error_default 错误处理程序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9711077/

相关文章:

python - 如何全屏显示绘图

python - 如何连接2个数组: 1 array contains string and the other array contains int64

python - python urllib2 会自动解压缩从网页获取的 gzip 数据吗?

python - 无法使用 urllib2 将内容类型设置为 application/json

python - 使用 stdout stdin 将数组从 C++ exe 传递到 Python

Python:对象没有属性

python - 使用 dateutil.parser 解析不完整日期时,如何将日期设置为 1?

python - 使用 Python 的亚马逊社交网络

python - jython 使用 urllib2 发出请求 throw General SSLEngine

python - 在Python中,urllib2给出错误