参考:https://testerhome.com/topics/5276

har导出格式如下:

{
'log':
{
'pages': [],
'comment':
'exported @ 2019/6/28 15:01:27',
'entries':
[
{
'time': ,
'connection':
'ClientPort:50377;
EgressPort:53633',
'comment': '[#43]',
'request':
{
'headersSize': ,
'postData': {
'text': '{
"checksum":"1557025867",
"language":""
}',
'mimeType': 'application/json'
},
'queryString': [],
'headers': [
{
'name': 'Host',
'value': 'bankpreidc.zatech.com'
},
{
'name': 'Content-Type',
'value': 'application/json'
},
{
'name': 'channelId',
'value': '10000'
},
{'name': 'Accept', 'value':'heheh'},
{'name': 'timestamp', 'value': '1561693450'},
{'name': 'appVersion', 'value': 'v1.0.0'},
{'name': 'OS', 'value': 'iOS'},
{'name': 'Accept-Encoding', 'value': 'gzip;q=1.0, compress;q=0.5'},
{'name': 'apiVersion', 'value': 'v1.0.0'},
{'name': 'Accept-Language', 'value': 'zh-Hans-CN;q=1.0'},
{'name': 'language', 'value': 'zh'},
{'name': 'did', 'value': 'NTIzOTIxNDYwMzMyM2NjZjk1OGM5NjBmYzNlNzg2OTYtZTkxNzg1MzYzNjA4NGM0Mjg4Njg3MmFhNzExMDE1YTgwMDAyLXIwWUtuK0MrS1Y2eDBteWs3WnhDYmQ2ZnovTT0='}, {'name': 'User-Agent', 'value': 'AnAnLifeInsurance_iOS/1.0.0 (com.zhonganio.zabank; build:357; iOS 11.4.1) Alamofire/4.8.2'},
{'name': 'Content-Length', 'value': '39'},
{'name': 'Connection','value': 'keep-alive'},
{'name': 'reqSeq', 'value': '9d3157c83dc46cd64cc65694c39163ba'},
{'name': 'OSVersion', 'value': '11.4.1'}
],
'bodySize': ,
'url': 'https://XXXXX/ci/dict/find',
'cookies': [],
'method': 'POST',
'httpVersion': 'HTTP/1.1'
},
'timings':
{
'blocked': -1,
'ssl': ,
'receive': ,
'wait': ,
'dns': ,
'send': , 'connect':
},
'response':
{
'headersSize': ,
'bodySize': ,
'statusText': '200',
'redirectURL': '',
'status': ,
'httpVersion': 'HTTP/1.1',
'cookies': [],
'content':
{
'compression': -259,
'comment': 'Body length exceeded fiddler.importexport.HTTPArchiveJSON.MaxTextBodyLength, so body was omitted.',
'size': ,
'mimeType': 'application/json;charset=UTF-8'
},
'headers':
[
{'name': 'Server', 'value': 'nginx'},
{'name': 'Date', 'value': 'Fri, 28 Jun 2019 03:44:13 GMT'},
{'name': 'Content-Type', 'value': 'application/json;charset=UTF-8'},
{'name': 'Transfer-Encoding', 'value': 'chunked'},
{'name': 'Connection', 'value': 'keep-alive'},
{'name': 'X-Application-Context', 'value': 'za-bank-gateway:8080'}
]
},
'startedDateTime': '2019-06-28T11:43:16.0675861+08:00',
'cache': {}
},
{
XXXX
},
。。。
],
'creator':
{
'name': 'Fiddler',
'comment': 'https://fiddler2.com',
'version': '5.0.20182.28034'
},
'version': '1.2'
}
}
代码如下:

#!/usr/bin/env python
# -*- coding: utf-8 -*-
from optparse import OptionParser
import os
import sys
import json # check env
if sys.version_info < (3, 4):
raise RuntimeError('At least Python 3.4 is required.') restype = ('js', 'css', 'jpg', 'gif', 'ico', 'png') def list2dic(headers):
header_dic = dict()
for head in headers:
if head['name'] in header_dic:
header_dic[head['name']] = header_dic[head['name']] + ',' + head['value']
else:
header_dic[head['name']] = head['value']
return header_dic def dictoand(dct):
res_list = list()
for tp in dct:
res_list.append('%s=%s' % (tp['name'], tp['value']))
return '&'.join(res_list) def dict2lr(lrsc):
tmpl = '''
web_custom_request("%(name)s",
"URL=%(url)s",
"Method=%(method)s",
"Resource=%(res)s",
"Referer=%(referer)s",
"EncType=%(enctype)s",
"Body=%(body)s",
LAST);'''
# url
url = lrsc['url']
method = lrsc['method']
name = url.split('/')[-1]
name = name.split('?')[0]
suff = url.split('.')[-1]
# Resource type
global restype
res = '0'
if suff in restype:
res = '1' # Content-Type
enctype = ''
if 'Content-Type' in lrsc:
enctype = lrsc['Content-Type']
# Referer
referer = ''
if 'Referer' in lrsc:
referer = lrsc['Referer'] # Body
body = ''
if 'posttext' in lrsc:
body = lrsc['posttext']
elif 'postparams' in lrsc:
body = dictoand(lrsc['postparams'])
body = body.replace('"', '\\"')
res = tmpl % {'name': name, 'url': url, 'method': method, 'enctype': enctype, 'referer': referer, 'res': res,
'body': body}
# Head
if 'SOAPAction' in lrsc:
res = ("\n" + ' web_add_header("SOAPAction", "%s")' + ";\n" + res) % lrsc['SOAPAction']
return res def parhar(harfile):
print('harfile:',harfile)
res = list()
try:
import codecs
# with codecs.open(harfile, 'r', 'utf-8-sig') as in_file:
# for line in in_file.readlines():
# print(line)
FH = codecs.open(harfile, mode='r', encoding='utf-8-sig')
# FH = open(harfile, mode='r')
print('FH:',FH)
all = json.load(FH)
FH.close()
except Exception as ex:
print('Open har file errr: %s' % ex)
quit() print(all)
har_ver = all['log']['version']
creater = all['log']['creator']['name']
entries = all['log']['entries']
ct = len(entries) # 请求实体数据
for et in entries:
stm = et['startedDateTime']
req = et['request'] # 请求数据
rsp = et['response'] # 返回数据
lrsc = dict()
if '_charlesStatus' in rsp and rsp['_charlesStatus'] != 'Complete':
continue
# 获取请求入参的主要数据
lrsc['method'] = req['method']
lrsc['url'] = req['url']
headers = req['headers']
print('headers:', headers)
# http head
header_dic = list2dic(headers)
print('headers dict:', header_dic)
if 'SOAPAction' in header_dic:
lrsc['SOAPAction'] = header_dic['SOAPAction'].replace('"', '\\"')
if 'Referer' in header_dic:
lrsc['Referer'] = header_dic['Referer']
if 'Content-Type' in header_dic:
lrsc['Content-Type'] = header_dic['Content-Type']
if lrsc['method'] == 'GET':
pass
elif lrsc['method'] == 'POST':
if 'postData' in req:
if 'text' in req['postData']:
lrsc['posttext'] = req['postData']['text']
if 'params' in req['postData']:
lrsc['postparams'] = req['postData']['params']
if 'mimeType' in req['postData']:
lrsc['postmime'] = req['postData']['mimeType']
else:
continue
print('V:',lrsc)
res.append(dict2lr(lrsc))
return res if __name__ == '__main__':
parse = OptionParser()
parse.add_option("-f", action="store", dest="harfile", help='harfile path')
parse.add_option("-o", action="store", dest="lrfile", help='action.c path')
(options, args) = parse.parse_args()
print('-----------------------')
print(options)
print('-----------------------')
print(args) if options.harfile is None or options.lrfile is None:
parse.print_help()
quit()
if not os.path.exists(options.harfile):
print('Har file %s not exist' % options.harfile)
quit()
print("1")
res = parhar(options.harfile)
print("**********************************8888888")
print(res)
file = open(options.lrfile, mode='w', encoding='utf-8')
for sc in res:
file.write(sc)
file.write("\n")
file.close()
print('Output to %s' % options.lrfile)

pytho 解析fiddler 导出的har文件代码,自动录入api的更多相关文章

  1. eclipse 设置打开java文件代码自动折叠

    eclipse 设置打开java文件代码自动折叠 java: windows/preference/java/editor/folding->enable folding 可以在里面设置所要折叠 ...

  2. java poi导出EXCEL xls文件代码

    String _currentPage = request.getParameter("currentPage"); Integer currentPage = 0; if(_cu ...

  3. 设置Eclipse的类文件和xml文件代码自动补全

    原文:https://blog.csdn.net/erlian1992/article/details/53706736 我们在平常编写代码的时候,不会记住大多数的类和文件的属性,方法等等,这就需要我 ...

  4. thinkphp5自动生成文档/注释代码自动生成api文档

    composer require weiwei/api-doc dev-master 安装之后,readme 有详细的使用说明代码: 部分界面: gitbub:https://github.com/z ...

  5. Fiddler抓包一键生成代码

    首先我们的需求场景是 用Fiddler抓到某个接口调用后,用代码来模拟调用,一般我们写代码会有3个步骤: 1设置http请求相关的参数:header,method,url,cookie等 2设置pos ...

  6. Chrome保存的HAR文件怎么打开?

    - Chrome保存HAR 在Chrome中,在需要抓包的任意一个浏览器窗口,按F12,点Network页面,即可进入抓包界面,之后的所有网页交互操作产生的报文,都会在此列出. 在抓包的报文界面上右键 ...

  7. Python 解析har 文件将域名分类导出

    前言 作为程序员平时主要是使用 shadowsocks 作为代理工具的.shadowsocks 有个很明显的优点儿就是可以设置白名单和黑名单.白名单是会走shadowsocks的自动代理模式. 遇到的 ...

  8. html文件在head标签中引入js地址和直接写js代码,所用时间是不同的,因为引入js地址,文件加载的时候需要通过通讯协议去解析地址,读取外部文件

    html文件在head标签中引入js地址和直接写js代码,所用时间是不同的,因为引入js地址,文件加载的时候需要通过通讯协议去解析地址,读取外部文件

  9. Twaver的mono-desiner导出的json文件解析

    以画的交换机为例,其他大概都差不多. 利用Twaver做出交换机模型如图1所示,其中,每一个端口都是一个单独的对象.具体Twaver操作流程参见网址:http://twaver.servasoft.c ...

随机推荐

  1. python 并发编程 多进程 互斥锁 目录

    python 并发编程 多进程 互斥锁 模拟抢票 互斥锁与join区别

  2. 【Linux 环境搭建】ubuntu下nfs安装与配置

    (1)安装 #sudo apt-get install nfs-kernel-server portmap(2)修改配置文件 修改/etc/exports,增加以下内容, /root/wksp/roo ...

  3. IntelliJ IDEA中创建Web聚合项目(Maven多模块项目)(转载)

    创建parent项目 1.打开IDEA,注意这里不要勾选模板,用模板创建过maven项目的小伙伴都知道模板创建项目非常慢,所以这里不要选模板,需要的文件夹我们后面自己来创建就可以了.所以这个页面直接点 ...

  4. python列表的复制,扯一下浅拷贝与深拷贝的区别

    将一个列表的数据复制到另一个列表中.使用列表[:],可以调用copy模块 import copy A = [21,22,23,24,['a','b','c','d'],25,26] B = A #直接 ...

  5. HTML面试问题收集(1)

    1.浏览器页面有哪三层构成,分别是什么,作用是什么? 构成:结构层.表示层.行为层分别是:HTML.CSS.JavaScript 作用:HTML实现页面结构,CSS完成页面的表现与风格,JavaScr ...

  6. webdriver 的使用 java 和python 两个版本

    在使用webdriver前要先做下准备,1.下载相应的支持包,可以pom.xml文件引入 2.下载版本对应的浏览器驱动(我这里用的是chromedriver.exe),很多问题都是由于浏览器驱动引起的 ...

  7. CentOS7.6中 KVM虚拟机内存、CPU调整

    CentOS7.6中 KVM虚拟机内存.CPU调整 一.调小虚拟机内存 调小虚拟机内存可以动态实现,不用关机 1.查看当前内存大小 [root@heyong kvm]# virsh dominfo t ...

  8. 牛客练习赛53E 老瞎眼 pk 小鲜肉(线段树)

    链接:https://ac.nowcoder.com/acm/contest/1114/E来源:牛客网题目:老瞎眼有一个长度为 n 的数组 a,为了为难小鲜肉,他准备了 Q 次询问,每次给出 一个区间 ...

  9. Vue获取dom元素

     <li  @click='获取li标签'    :ref="center-li" id="center-li"      > =====我是li标 ...

  10. mysql 中文乱码 修改编码 utf8

    在安装完数据库的时候,先不要创建数据库,先去更改字符集设置. show variables like 'character%'; vim /etc/my.cnf   (注意 下面的字段文件内没有时,自 ...