我目前正在尝试使用 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
如果您需要的只是停止重定向,那么有一个简单的方法可以做到这一点。例如,我只想获取 cookie,为了获得更好的性能,我不想重定向到任何其他页面。我也希望代码保留为 3xx。我们以 302 为例。
class MyHTTPErrorProcessor(urllib2.HTTPErrorProcessor):
def http_response(self, request, response):
code, msg, hdrs = response.code, response.msg, response.info()
# only add this line to stop 302 redirection.
if code == 302: return response
if not (200 <= code < 300):
response = self.parent.error(
'http', request, response, code, msg, hdrs)
return response
https_response = http_response
cj = cookielib.CookieJar()
opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(cj), MyHTTPErrorProcessor)
这样,你甚至不需要进入urllib2.HTTPRedirectHandler.http_error_302()
更常见的情况是我们只是想停止重定向(根据需要):
class NoRedirection(urllib2.HTTPErrorProcessor):
def http_response(self, request, response):
return response
https_response = http_response
通常这样使用:
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']
urllib2.urlopen
调用 build_opener()
,它使用此处理程序类列表:
handlers = [ProxyHandler, UnknownHandler, HTTPHandler,
HTTPDefaultErrorHandler, HTTPRedirectHandler,
FTPHandler, FileHandler, HTTPErrorProcessor]
您可以尝试使用省略
urllib2.build_opener(handlers)
的列表自行调用 HTTPRedirectHandler
,然后对结果调用 open()
方法来打开您的 URL。如果您真的不喜欢重定向,您甚至可以调用 urllib2.install_opener(opener)
到您自己的非重定向开启器。
听起来你真正的问题是
urllib2
没有按照你想要的方式做cookie。另请参阅如何使用Python登录网页并检索cookie以供以后使用?