python urllib2 解决重定向问题
来源:互联网 发布:linux文件分别打包命令 编辑:程序博客网 时间:2024/06/01 13:23
原文地址:https://stackoverflow.com/questions/554446/how-do-i-prevent-pythons-urllib2-from-following-a-redirect
由于urllib2处理重定向不会自动带上cookie,这个是比较麻烦的,找了几篇文章,还是这个靠谱,加上去以备万一。
1 以下代码是使得urllib2拥有重定向带上cookie
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_302cookieprocessor = urllib2.HTTPCookieProcessor()opener = urllib2.build_opener(MyHTTPRedirectHandler, cookieprocessor)urllib2.install_opener(opener)response =urllib2.urlopen("WHEREEVER")print response.read()print cookieprocessor.cookiejar
2 以下代码是阻止重定向,并且获得响应页面(非重定向之后的页面)。
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_responsecj = cookielib.CookieJar()opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(cj), MyHTTPErrorProcessor)
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']这里响应头部的Location字段就是重定向的url。
接下来的文章会利用这两个测试学校图书馆用户登录的问题
阅读全文
0 0
- python urllib2 解决重定向问题
- python urllib2处理重定向的问题
- python爬虫解决网页重定向问题
- python爬虫解决网页重定向问题
- python解决urllib2乱码问题
- 【python】解决urllib2乱码问题
- cookie重定向问题的解决!
- ICMP重定向问题的解决
- SpyHunter解决Chrome重定向searchinterneat问题
- 爬虫解决网页重定向问题
- python 调用smtplib输出重定向问题
- python爬虫<解决URL被重定向无法抓取到数据问题>
- python 的重定向
- [python]重定向输出
- python重定向
- python 重定向
- python重定向
- python 输出重定向
- Cocos2d-x客户端资源加密
- Spring有多个配置文件整合一个
- 《HBase权威指南》读书笔记 第八章:架构,LSM树
- 从环境云网站爬取数据
- 异步高并发web框架 sanic 官方教程
- python urllib2 解决重定向问题
- java随笔_1
- 微分享-spring线程池实战
- new和molloc的区别
- 查看android进程信息
- 什么是POD数据类型?
- 两点补充——CSS3新属性以及弹性布局
- 异常
- Linux模拟三路由实验