参考: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中并没有关键字const,在 ...

  2. mysql: show full processlist 详解

    show full processlist 是显示用户正在运行的线程,需要注意的是,除了 root 用户能看到所有正在运行的线程外,其他用户都只能看到自己正在运行的线程,看不到其它用户正在运行的线程. ...

  3. Zend_Cache的使用

    一.Zend_Cache快速浏览 Zend_Cache 提供了一个缓存任何数据的一般方法. 在Zend Framework中缓存由前端操作,同时通过后端适配器(File, Sqlite, Memcac ...

  4. 嗨翻C语言--这里没有蠢问题(一)

    问:card_name[0]是什么意思?答:它是用户输入的第一个字符.如果用户输入了10,那么card_name[0]就将是1.问:总是得用/*和*/写注释吗?答:如果你的编译器支持C99标准,就可以 ...

  5. c++多线程并发学习笔记(0)

    多进程并发:将应用程序分为多个独立的进程,它们在同一时刻运行.如图所示,独立的进程可以通过进程间常规的通信渠道传递讯息(信号.套接字..文件.管道等等). 优点:1.操作系统在进程间提供附附加的保护操 ...

  6. 剑指offer-序列化和反序列化二叉树-树-python

    题目描述 请实现两个函数,分别用来序列化和反序列化二叉树   二叉树的序列化是指:把一棵二叉树按照某种遍历方式的结果以某种格式保存为字符串,从而使得内存中建立起来的二叉树可以持久保存.序列化可以基于先 ...

  7. 数组和datatable间的相互转换[C#]

    byte[] LogMsgByte = null; DataTable dtMessageInfo = new DataTable(); //将datatable转换为数组 dtMessageInfo ...

  8. 将Medium中的博客导出成markdown

    Medium(https://medium.com)(需要翻墙访问)是国外非常知名的一个博客平台.上面经常有很多知名的技术大牛在上面发布博客,现在一般国内的搬运的技术文章大多数都是来自于这个平台. M ...

  9. memset,内存初始化函数

    # include <string.h> void *memset(void *s, int c, unsigned long n); 函数的功能是:将指针变量 s 所指向的前 n 字节的 ...

  10. 详解 nginx.conf 配置文件

    Nginx 配置文件主要分为 4 部分: Main 全局设置:影响其他所有设置 Server 主机设置:配置指定的主机和端口 Upstream 负载均衡服务器设置 :设置一系列的后置服务器 Locat ...