If you only need to stop the redirect, then there is an easy way to do this. For example, I want to receive cookies and for best performance I don’t want to be redirected to any other page. I also hope that the code will be saved as 3xx. let's say, for example, 302.
class MyHTTPErrorProcessor(urllib2.HTTPErrorProcessor): def http_response(self, request, response): code, msg, hdrs = response.code, response.msg, response.info()
That way you don’t even have to go into urllib2.HTTPRedirectHandler.http_error_302 ()
Even more common is that we just want to stop the redirect (as needed):
class NoRedirection(urllib2.HTTPErrorProcessor): def http_response(self, request, response): return response https_response = http_response
And usually use it like this:
cj = cookielib.CookieJar() opener = urllib2.build_opener(NoRedirection, urllib2.HTTPCookieProcessor(cj)) data = {} response = opener.open('http://www.example.com', urllib.urlencode(data)) if response.code == 302: redirection_target = response.headers['Location']
Alan Duan Jul 31 '12 at 16:33 2012-07-31 16:33
source share