如何防止 Python 的 urllib(2) 遵循重定向
题
我目前正在尝试使用 Python 登录网站,但是该网站似乎在同一页面上发送 cookie 和重定向语句。Python 似乎遵循该重定向,从而阻止我读取登录页面发送的 cookie。如何防止 Python 的 urllib(或 urllib2)urlopen 遵循重定向?
解决方案
你可以做几件事:
- 构建您自己的 HTTPRedirectHandler 来拦截每个重定向
- 创建 HTTPCookieProcessor 的实例并安装该 opener,以便您可以访问 cookiejar。
这是一个快速的小事情,同时显示了
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
其他提示
如果你需要的是停止重定向,然后有一个简单的方法来做到这一点。例如,我只想要得到的cookies和更好的表现,我不希望被重定向到任何其他页面。此外,我希望代码保持为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()
方法来打开你的网址。如果你真的不喜欢重定向,你甚至可以打电话给urllib2.install_opener(opener)
自己的非重定向揭幕战。
这听起来像你真正的问题是,urllib2
是不是做饼干你想要的方式。另请参见如何使用Python登录到一个网页,检索cookie以便将来使用?
不隶属于 StackOverflow