参考: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. ubutnu同时安装OpenCV2和OpenCV3及contrib

    1.OpenCV2源码安装 安装依赖项 sudo apt-get install build-essential //build-essential是c语言的开发包,包含了gcc make gdb和l ...

  2. Js AJAX Event

    ;(function () { if ( typeof window.CustomEvent === "function" ) return false; function Cus ...

  3. [DS+Algo] 006 两种简单排序及其代码实现

    目录 1. 快速排序 QuickSort 1.1 步骤 1.2 性能分析 1.3 Python 代码示例 2. 归并排序 MergeSort 2.1 步骤 2.2 性能分析 2.3 Python 代码 ...

  4. Java - Java Mail邮件开发(2)springboot +Java Mail + Html

    1.springboot + Java Mail + Html 项目结构: pom.xml <project xmlns="http://maven.apache.org/POM/4. ...

  5. 剑指Offer编程题(Java实现)——删除链表中重复的结点

    题目描述 在一个排序的链表中,存在重复的结点,请删除该链表中重复的结点,重复的结点不保留,返回链表头指针. 例如,链表1->2->3->3->4->4->5 处理后 ...

  6. The order of a Tree

    The order of a Tree Problem Description As we know,the shape of a binary search tree is greatly rela ...

  7. 题解 CF1140D 【Minimum Triangulation】

    题意:求将一个n边形分解成(n-2)个三边形花费的最小精力,其中花费的精力是所有三角形的三顶点编号乘积的和(其中编号是按照顶点的顺时针顺序编写的) 考虑1,x,y连了一个三角形,x,y,z连了一个三角 ...

  8. JetBrains视图

    三种视图模式:

  9. loli的测试-2018.12.9

    模拟赛-2018.12.9 这是NOIP之后第一次模拟赛...但是考的比较悲惨. 非常喜欢写考试总结,不知道为什么... T1:https://www.luogu.org/problemnew/sho ...

  10. WordPress用户的权限类

    WordPress的权限类这是管理 WordPress 用户权限最常用的函数.WordPress 用于角色和权限幕后工作的三个类,以及这些类提供的接口,我们可以在插件中进行高级权限管理.这三个类是: ...