捕获 http 错误 [英] Catching http errors

查看:32
本文介绍了捕获 http 错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

例如,如何在 python 和 urllib(2) 中捕获页面的 404 和 403 错误?

how can I catch the 404 and 403 errors for pages in python and urllib(2), for example?

有没有大类包装器的快速方法?

Are there any fast ways without big class-wrappers?

添加信息(堆栈跟踪):

Added info (stack trace):

Traceback (most recent call last):
  File "test.py", line 3, in <module>
    page = urllib2.urlopen("http://localhost:4444")
  File "/usr/lib/python2.6/urllib2.py", line 126, in urlopen
    return _opener.open(url, data, timeout)
  File "/usr/lib/python2.6/urllib2.py", line 391, in open
    response = self._open(req, data)
  File "/usr/lib/python2.6/urllib2.py", line 409, in _open
    '_open', req)
  File "/usr/lib/python2.6/urllib2.py", line 369, in _call_chain
    result = func(*args)
  File "/usr/lib/python2.6/urllib2.py", line 1161, in http_open
    return self.do_open(httplib.HTTPConnection, req)
  File "/usr/lib/python2.6/urllib2.py", line 1136, in do_open
    raise URLError(err)
urllib2.URLError: <urlopen error [Errno 111] Connection refused>

推荐答案

import urllib2 
try:
   page = urllib2.urlopen("some url")
except urllib2.HTTPError, err:
   if err.code == 404:
       print "Page not found!"
   elif err.code == 403:
       print "Access denied!"
   else:
       print "Something happened! Error code", err.code
except urllib2.URLError, err:
    print "Some other error happened:", err.reason

在您的情况下,错误已经在建立 HTTP 连接之前发生 - 因此您需要添加另一个捕获 URLError 的错误处理程序.但这与 404 或 403 错误无关.

In your case, the error happens already before the HTTP connection could be built - therefore you need to add another error handler that catches URLError. But this has nothing to do with 404 or 403 errors.

这篇关于捕获 http 错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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