用 HttpAnalyzer 记录的多行 header 数据生成 header(原创)

作者:汉学

原创作品,转载请保留出处 http://www.cnblogs.com/c2soft

在使用 HttpAnalyzer 等工具抓包时,同时选择多行 header 数据可以方便地保存 header,使用下面代码可以方便地将多行数据重新组装成 header并附加到 request 上。

refresh_header = '''
Connection:keep-alive
Accept:text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8
Upgrade-Insecure-Requests:1
User-Agent:Mozilla/5.0 (Windows NT 5.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/49.0.2623.112 Safari/537.36
Referer:https://pan.baidu.com/controller/help/HelpController.jpf
Accept-Encoding:gzip, deflate, sdch
Accept-Language:zh-CN,zh;q=0.8
'''

def MakeHeader(headerText):
    s = headerText.strip().split('\n')
    s = {x.split(':', 1)[0] : x.split(':', 1)[1] for x in s}
    return s

def RefreshNum(session, CourseIndex, CourseId):
    data = {}
    data['index'] = CourseIndex
    data['seq'] = CourseId

    headers = MakeHeader(refresh_header)
    
    i = 0
    while i < 4:
        try:
            content = session.post(refresh_url, data=data, headers=headers, timeout=3)
            # 将返回的字符串转换成字典(字符串中必须用双引号,如{"electedNum":"190"},这是json的要求)
            #ret = json.loads(content.text)
            #return int(ret['electedNum'])
            
            ret = re.search('"electedNum":"(.*)"', content.text)
            if ret:
                return int(ret.group(1))
            else:
                with open(time.strftime('dump_refresh_%m%d_%H%M%S.html'), 'w', encoding='utf-8') as f:
                    f.write(content.text)             
                return -1           
        except Exception as e:
            i += 1
    return 0

 

posted @ 2020-05-31 16:17  汉学  阅读(191)  评论(0)    收藏  举报