在Python中使用Mechanize获取和捕获HTTP响应

12 投票
2 回答
9227 浏览
提问于 2025-04-15 21:48

我正在尝试在Python中使用Mechanize获取响应代码。虽然我能得到一个200的状态码,但其他的状态码却没有返回(404会抛出异常,而30x的状态码会被忽略)。有没有办法获取原始的状态码呢?

谢谢

2 个回答

0

在twill中,输入 get_browser().get_code()

twill 是一个很棒的自动化和测试工具,它是基于mechanize开发的,目的是让使用起来更简单。这个工具真的非常方便。

13

错误会引发一个异常,所以你只需要使用 try:...except:... 来处理这些错误。

你的 Mechanize 浏览器对象有一个方法叫 set_handle_redirect(),你可以用它来开启或关闭 30x 重定向。如果你把它关掉,当发生重定向时就会出现错误,你可以像处理其他错误一样来处理它:

>>> from mechanize import Browser
>>> browser = Browser()
>>> resp = browser.open('http://www.oxfam.com') # this generates a redirect
>>> resp.geturl()
'http://www.oxfam.org/'
>>> browser.set_handle_redirect(False)
>>> resp = browser.open('http://www.oxfam.com')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "build\bdist.win32\egg\mechanize\_mechanize.py", line 209, in open
  File "build\bdist.win32\egg\mechanize\_mechanize.py", line 261, in _mech_open
mechanize._response.httperror_seek_wrapper: HTTP Error 301: Moved Permanently
>>>
>>> from urllib2 import HTTPError
>>> try:
...    resp = browser.open('http://www.oxfam.com')
... except HTTPError, e:
...    print "Got error code", e.code
...
Got error code 301

撰写回答