我想从python中的Mechanize获取响应代码。虽然我能够获得200状态码,但其他任何内容都不会被返回(404抛出,异常和30x被忽略)。有没有办法获得原始状态码?使用Python中的机械化获取和捕获HTTP响应
感谢
我想从python中的Mechanize获取响应代码。虽然我能够获得200状态码,但其他任何内容都不会被返回(404抛出,异常和30x被忽略)。有没有办法获得原始状态码?使用Python中的机械化获取和捕获HTTP响应
感谢
错误会抛出异常,所以只使用try:...除了:...来处理它们。
您的机械化浏览器对象有一个方法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
在斜纹布,做get_browser().get_code()
twill是建立在机械化的顶部突出的自动化和测试层,使其更易于使用。这非常方便。