【Python网页分析】httplib库的重定向处理

1. 网页处理

下图是实际操作抓包分析结果,其他的步骤不再描述。

1、从选定的POST /main.aspx开始

2、后面服务器回复302重定向到/cd_chose.aspx页面

3、抓包数据有GET重定向URL,GET css和js文件不再赘述

4、POST到/cd_chose.aspx

2. Python模拟

2.1 抓包分析,后面的GET方法发送不去

再查看IE上抓包结果

没有出现GET方法

怀疑是需要直接POST,尝试了之后仍然失败,但仔细看了下POST内容,头里面有GET头,由于不太了解IE的头显示,不再深究。

2.2 检查消息格式

由于GET这个重定向页面之前定义了HTTP头,

对比网页上实际操作成功发送的头,发现我在Python中多定义了一个头”Content-Type",主要是前面的POST方法需要和头

实际流程里面,前面其他GET消息需要这个头,但本消息中确实不需要这个头。

去掉这个头

查看Python的消息流程正常

这个问题由于自己http基础不踏实,遇到问题不太确定方向,总觉得重定向流程有什么其他的复杂处理。耽搁了很多时间,

结果其实就只是一个头的问题。

最后附上封装的http get和post方法,调用的httplib库,比较灵活方便,可以根据前端js代码,模仿自己生成一些特殊字段认证服务器。

def http_get(self,connDefault=None,url=‘‘,bodyFlag=False,refererFresh=False,referer = ‘‘):

status,infor = 1,‘‘       
        if connDefault is None:
            conn = HTTPConnection(self.host,timeout=60)
        else:
            conn = connDefault

try:

print ‘http_get -> enter to get ‘,url
            start = time.time()           
           
            print ‘http_get -> connect init OK‘
            conn.request(‘GET‘,url,headers=self.headers)

print ‘http_get -> wait the  response...‘
            response = conn.getresponse()
            end = time.time()
            print "http_get -> info:",end - start,response.status

print ‘http_get -> response headers‘ ,response.getheaders()

#状态码
            status = response.status
            if status != 200:
                print ‘http_get -> http status error‘,status
                infor = ‘error‘

else:
                #获取Cookie,格式如下ASP.NET_SessionId=pzt0bs55tc2fjrbv0canht45; path=/; HttpOnly
                cookie=response.getheader(‘Set-Cookie‘,‘‘)
                #print "http_get -> cookie -> ",cookie

"""
                Cookie叠加
                """
                if cookie != ‘‘:
                    #cookie键值分两种类型
                    print ‘http_get -> peer Set-Cookie‘  , cookie
                    pattern = re.compile(r‘(key=[\w=+/]+;|ASP.NET_SessionId=[\w=+/]+;)‘)
                    _list = pattern.search(cookie)
                    #print ‘http_get -> _list‘,_list   
                    if _list is not None:
                        #print ‘http_get -> _list‘ ,url,_list.groups()
                        oCookie = self.headers.get(‘Cookie‘,‘‘)
                        if oCookie == ‘‘:
                            self.headers["Cookie"] = str(_list.groups()[0][:-1])
                        else:
                            self.headers["Cookie"] = oCookie + ‘;‘  + str(_list.groups()[0][:-1])
                        print ‘http_get -> request Cookie‘ ,self.headers["Cookie"]
                    else:
                        pass
                else:
                    pass

"""
                更新Referer
                """

if refererFresh:
                    if referer != ‘‘:
                        self.headers["Referer"] = "http://" + self.host + referer
                    else:
                        self.headers["Referer"] = "http://" + self.host + url

#获取编码格式,gzip编码会在头中显示定义
                content_encoding = response.getheader(‘Content-Encoding‘,‘‘)
                if bodyFlag:
                    """
                    gzip解码
                    """
                    if content_encoding == ‘gzip‘:
                        buf = StringIO(response.read())
                        infor = GzipFile(fileobj=buf).read()
                    else:
                        infor = response.read()

except Exception,ex:
            print ‘http_get -> error:‘,ex
            status,infor = 1,ex
        finally:
            if connDefault is None:
                conn.close()
            return status,infor

def http_post(self,connDefault=None,url=‘‘,PostStr=‘‘):
        status,response = 1,‘‘
        try:
            headers = deepcopy(self.headers)
            headers["Content-Type"] ="application/x-www-form-urlencoded"
            start = time.time()
            if connDefault is None:
                conn = HTTPConnection(self.host,timeout=60)
            else:
                conn = connDefault

headers["Content-Length"] = len(PostStr)
            conn.request(‘POST‘,url,PostStr,headers=headers)
            response = conn.getresponse()
            end = time.time()
            print "http_post info:",end - start,response.status
           
            #重定向
            if response.status == 302:
                Location=response.getheader(‘Location‘,‘‘)
                status,response = 302,Location
            #正常提交
            elif response.status == 200:
                status,response = 200,‘‘
            else:
                status,response = response.status,‘does not support‘
        except Exception,ex:
            print ‘http_post -> error:‘,ex
            status,response = 1,ex
        finally:
            if connDefault is None:
                conn.close()
            return status,response

时间: 2024-08-05 11:17:35

【Python网页分析】httplib库的重定向处理的相关文章

Python爬虫的Urllib库有哪些高级用法?

本文和大家分享的主要是python爬虫的Urllib库的高级用法相关内容,一起来看看吧,希望对大家学习python有所帮助. 1.分分钟扒一个网页下来 怎样扒网页呢?其实就是根据URL来获取它的网页信息,虽然我们在浏览器中看到的是一幅幅优美的画面,但是其实是由浏览器解释才呈现出来的,实质它 是一段HTML代码,加 JS.CSS,如果把网页比作一个人,那么HTML便是他的骨架,JS便是他的肌肉,CSS便是它的衣服.所以最重要的部分是存在于HTML中的,下面我 们就写个例子来扒一个网页下来. imp

实战篇一 python常用模块和库介绍

# [email protected] coding: utf-8 [email protected] -- Python 常用模块和库介绍 第一部分:json模块介绍 import json 将一个Python数据结构转换为JSON: dict_ = {1:2, 3:4, "55":"66"} # test json.dumps print type(dict_), dict_ json_str = json.dumps(dict_) print "js

Python常用的标准库以及第三方库有哪些?

20个必不可少的Python库也是基本的第三方库 读者您好.今天我将介绍20个属于我常用工具的Python库,我相信你看完之后也会觉得离不开它们.他们是: Requests.Kenneth Reitz写的最富盛名的http库.每个Python程序员都应该有它. Scrapy.如果你从事爬虫相关的工作,那么这个库也是必不可少的.用过它之后你就不会再想用别的同类库了. wxPython.Python的一个GUI(图形用户界面)工具.我主要用它替代tkinter.你一定会爱上它的. Pillow.它是

Python 网页爬虫 & 文本处理 & 科学计算 & 机器学习 & 数据挖掘兵器谱(转)

原文:http://www.52nlp.cn/python-网页爬虫-文本处理-科学计算-机器学习-数据挖掘 曾经因为NLTK的缘故开始学习Python,之后渐渐成为我工作中的第一辅助脚本语言,虽然开发语言是C/C++,但平时的很多文本数据处理任务都交给了Python.离开腾讯创业后,第一个作品课程图谱也是选择了Python系的Flask框架,渐渐的将自己的绝大部分工作交给了Python.这些年来,接触和使用了很多Python工具包,特别是在文本处理,科学计算,机器学习和数据挖掘领域,有很多很多

【Python】Python 网页爬虫 & 文本处理 & 科学计算 & 机器学习 & 数据挖掘兵器谱

好文 mark http://www.52nlp.cn/python-%E7%BD%91%E9%A1%B5%E7%88%AC%E8%99%AB-%E6%96%87%E6%9C%AC%E5%A4%84%E7%90%86-%E7%A7%91%E5%AD%A6%E8%AE%A1%E7%AE%97-%E6%9C%BA%E5%99%A8%E5%AD%A6%E4%B9%A0-%E6%95%B0%E6%8D%AE%E6%8C%96%E6%8E%98 曾经因为NLTK的缘故开始学习Python,之后渐渐成为我工

Python代码分析工具:PyChecker、Pylint

1 概述 PyChecker是Python代码的静态分析工具,它能够帮助查找Python代码的bug,而且能够对代码的复杂度和格式等提出警告. PyChecker可以工作在多种方式之下.首先,PyChecker会导入所检查文件中包含的模块,检查导入是否正确,同时检查文件中的函数.类和方法等. PyChecker可以检查出来的问题有如下几种: 全局量没有找到,比如没有导入模块 传递给函数.方法.构造器的参数数目错误 传递给内建函数和方法的参数数目错误 字符串格式化信息不匹配 使用不存在的类方法和属

python爬虫基础03-requests库

优雅到骨子里的Requests 本文地址:https://www.jianshu.com/p/678489e022c8 简介 上一篇文章介绍了Python的网络请求库urllib和urllib3的使用方法,那么,作为同样是网络请求库的Requests,相对于urllib,有什么优点呢? 其实,只有两个词,简单优雅. Requests的宣言就是:HTTP for Humans.可以说,Requests彻底贯彻了Python所代表的简单优雅的精神. 之前的urllib做为Python的标准库,因为历

一个极其简洁的Python网页抓取程序

paip. 混合编程的实现resin4 (自带Quercus ) 配置 php 环境 #---混合编程的类型 1.代码inline 方式 2.使用库/api  解析方式. #----配置resin 支持php resin4默认自动支持php.. 也能手动配置了.web.xml加php的servlet解析..参考Quercus让你的PHP开心在Servlet容器奔跑 #----配置 php.ini路线 运行t.php,,看见 Configuration File (php.ini) Path =>

Python爬虫之Urllib库的基本使用

Python爬虫之Urllib库的基本使用 import urllib2 response = urllib2.urlopen("http://www.baidu.com") print response.read() 其实上面的urlopen参数可以传入一个request请求,它其实就是一个Request类的实例,构造时需要传入Url,Data等等的内容.比如上面的两行代码,我们可以这么改写 # -*- coding: utf-8 -*- """ Cre