Python的机械化模块错误

时间:2020-03-06 14:54:33  来源:igfitidea点击:

我正在使用mechanize模块来执行来自Python的一些网络查询。我希望我的程序具有容错能力,并能优雅地处理各种错误(错误的URL,403/404响应)。但是,在机械化文档中找不到因各种错误而引发的错误/异常。

我只是这样称呼它:

self.browser = mechanize.Browser()
    self.browser.addheaders = [('User-agent', browser_header)]

    self.browser.open(query_url)
    self.result_page = self.browser.response().read()

我怎么知道在这里可以抛出什么错误/异常并处理它们?

解决方案

我在他们的文档中发现了这一点:

One final thing to note is that there
  are some catch-all bare except:
  statements in the module, which are
  there to handle unexpected bad input
  without crashing your program. If this
  happens, it's a bug in mechanize, so
  please mail me the warning text.

所以我想他们不会提出任何例外。我们还可以在源代码中搜索Exception子类,并查看其用法。

$ perl -0777 -ne'print qq() if /__all__ = \[(.*?)\]/s' __init__.py | grep Error 

'BrowserStateError',
'ContentTooShortError',
'FormNotFoundError',
'GopherError',
'HTTPDefaultErrorHandler',
'HTTPError',
'HTTPErrorProcessor',
'LinkNotFoundError',
'LoadError',
'ParseError',
'RobotExclusionError',
'URLError',

或者:

>>> import mechanize
>>> filter(lambda s: "Error" in s, dir(mechanize))
['BrowserStateError', 'ContentTooShortError', 'FormNotFoundError', 'GopherError'
, 'HTTPDefaultErrorHandler', 'HTTPError', 'HTTPErrorProcessor', 'LinkNotFoundErr
or', 'LoadError', 'ParseError', 'RobotExclusionError', 'URLError']