在Python中使用Mechanize获取和捕获HTTP响应 [英] Getting and trapping HTTP response using Mechanize in Python

查看:44
本文介绍了在Python中使用Mechanize获取和捕获HTTP响应的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试从python中的Mechanize获取响应代码.虽然我能够获得200状态代码,但不会返回任何其他内容(404抛出异常,并且30x会被忽略).有没有办法获取原始状态码?

I am trying to get the response codes from Mechanize in python. While I am able to get a 200 status code anything else isn't returned (404 throws and exception and 30x is ignored). Is there a way to get the original status code?

谢谢

推荐答案

错误将引发异常,因此只需使用try:... except:...即可处理它们.

Errors will throw an exception, so just use try:...except:... to handle them.

您的机械化浏览器对象具有set_handle_redirect()方法,可用于打开或关闭30倍重定向.将其关闭后,您将收到一个处理重定向的错误,就像处理其他任何错误一样:

Your Mechanize browser object has a method set_handle_redirect() that you can use to turn 30x redirection on or off. Turn it off and you get an error for redirects that you handle just like you handle any other error:

>>> 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

这篇关于在Python中使用Mechanize获取和捕获HTTP响应的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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