我目前正在尝试使用Python登录网站,但是该网站似乎在同一页面上发送了cookie和重定向语句。Python似乎正在遵循该重定向,因此使我无法读取登录页面发送的cookie。如何防止Python的urllib(或urllib2)urlopen跟随重定向?
您可以做几件事:
这是一件快速的小事,既显示了
import urllib2 #redirect_handler = urllib2.HTTPRedirectHandler() class MyHTTPRedirectHandler(urllib2.HTTPRedirectHandler): def http_error_302(self, req, fp, code, msg, headers): print "Cookie Manip Right Here" return urllib2.HTTPRedirectHandler.http_error_302(self, req, fp, code, msg, headers) http_error_301 = http_error_303 = http_error_307 = http_error_302 cookieprocessor = urllib2.HTTPCookieProcessor() opener = urllib2.build_opener(MyHTTPRedirectHandler, cookieprocessor) urllib2.install_opener(opener) response =urllib2.urlopen("WHEREEVER") print response.read() print cookieprocessor.cookiejar