【发布时间】:2010-10-07 22:54:42
【问题描述】:
我目前正在尝试使用 Python 登录一个站点,但是该站点似乎在同一页面上发送了一个 cookie 和一个重定向语句。 Python 似乎遵循该重定向,因此阻止我读取登录页面发送的 cookie。如何防止 Python 的 urllib(或 urllib2)urlopen 跟随重定向?
【问题讨论】:
我目前正在尝试使用 Python 登录一个站点,但是该站点似乎在同一页面上发送了一个 cookie 和一个重定向语句。 Python 似乎遵循该重定向,因此阻止我读取登录页面发送的 cookie。如何防止 Python 的 urllib(或 urllib2)urlopen 跟随重定向?
【问题讨论】:
urllib2.urlopen 调用使用此处理程序类列表的build_opener():
handlers = [ProxyHandler, UnknownHandler, HTTPHandler,
HTTPDefaultErrorHandler, HTTPRedirectHandler,
FTPHandler, FileHandler, HTTPErrorProcessor]
您可以尝试使用省略HTTPRedirectHandler 的列表自己调用urllib2.build_opener(handlers),然后在结果上调用open() 方法以打开您的URL。如果你真的不喜欢重定向,你甚至可以调用urllib2.install_opener(opener) 到你自己的非重定向开启者。
听起来你真正的问题是urllib2 没有按照你想要的方式做 cookie。另见How to use Python to login to a webpage and retrieve cookies for later usage?
【讨论】:
HTTPRedirectHandler 不起作用...
你可以做几件事:
这是一个快速的小东西,显示了两者
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
【讨论】:
redirect_handler = urllib2.HTTPRedirectHandler()。你要展示第二个例子吗?
MyHTTPRedirectHandler,而是将类传递给build_opener()方法?
如果您只需要停止重定向,那么有一种简单的方法可以做到这一点。例如,我只想获取 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']
【讨论】:
class NoRedirection() - 你甚至不必存储 code, msg, hdrs -- 谢谢 Alan。