我目前正在尝试使用Python登录网站,但该网站似乎在同一页面上发送cookie和重定向语句.Python似乎遵循该重定向,从而阻止我阅读登录页面发送的cookie.如何防止Python的urllib(或urllib2)urlopen跟随重定向?
pop*_*ope 33
你可以做几件事:
这是一个显示两者的快速小事
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
Run Code Online (Sandbox Code Playgroud)
Ala*_*uan 29
如果您只需要停止重定向,那么有一种简单的方法可以做到这一点.例如,我只想获取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)
Run Code Online (Sandbox Code Playgroud)
这样,你甚至不需要进入urllib2.HTTPRedirectHandler.http_error_302()
更常见的情况是我们只想停止重定向(根据需要):
class NoRedirection(urllib2.HTTPErrorProcessor):
def http_response(self, request, response):
return response
https_response = http_response
Run Code Online (Sandbox Code Playgroud)
通常以这种方式使用它:
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']
Run Code Online (Sandbox Code Playgroud)
joe*_*ker 12
urllib2.urlopenbuild_opener()使用此处理程序类列表的调用:
handlers = [ProxyHandler, UnknownHandler, HTTPHandler,
HTTPDefaultErrorHandler, HTTPRedirectHandler,
FTPHandler, FileHandler, HTTPErrorProcessor]
Run Code Online (Sandbox Code Playgroud)
您可以尝试urllib2.build_opener(handlers)使用省略的列表调用自己HTTPRedirectHandler,然后open()在结果上调用方法以打开您的URL.如果你真的不喜欢重定向,你甚至可以打电话urllib2.install_opener(opener)给你自己的非重定向开启者.
这听起来像你真正的问题是urllib2没有按照你想要的方式做饼干.另请参阅如何使用Python登录网页并检索cookie以供以后使用?
| 归档时间: |
|
| 查看次数: |
39694 次 |
| 最近记录: |