通過百度 OCR 工具識別 rap2 登入中的驗證碼,從而實現登入~那我們今天來實戰解析 rap2 的介面資料,生成我們所需要的介面資料
實踐上手
文件分析
1、我們先通過 F12 看看哪個介面是我們需要的?對~就是你了!

2、將介面資料複製到https://www.json.cn/,我們來看看介面資料結構,看看有哪些資訊是需要的


3、通過分析 properties 中的資料,發現 pos=1 為請求頭,pos=2 為路徑引數,pos=3 為 body 引數,name 為欄位名,value 為欄位值,parentId=1,沒有父節點;parentId!=-1,為父節點


程式碼解析
上一期中,有小夥伴反饋說,可以輸入 cookies 不?那這次優化一下吧~
實現 rap2 登入並獲取資料
@classmethod
def rap_data(cls, id, cookies = None):
"""
獲取介面文件資料
:param id: 介面文件id
:param cookies: 非必填,登入的cookies
:return: 返回json資料
"""
params = {"id": id}
if cookies:
try:
cls.cookies = dict([i.split("=", 1) for i in cookies.split("; ")])
except Exception as e:
raise Exception('cookies格式不對,請重新輸入!')
try:
res = requests.get(url=UrlConfig.RAP_PROJRCT_URL, params=params, cookies=cls.cookies).json()
except Exception as e:
raise Exception('cookies過期了,請重新輸入!')
return res
else:
login_result = False
#判斷是否登入成功
while not login_result:
login_result = Rap2Data.rap_login()
res = requests.get(url=UrlConfig.RAP_PROJRCT_URL, params=params, cookies=cls.cookies).json()
return res
解析關鍵程式碼展示:執行主入口
class Rap2Parse(object):
@classmethod
def api_data(cls, id, cookies=None, module=None):
json_obj = Rap2Data.rap_data(id, cookies)
errMsg = json_obj.get("errMsg")
#獲取報錯資訊,將其丟擲(許可權不足、不存在介面文件,介面都會返回errMsg)
if errMsg:
errMsg = errMsg + f"請將介面文件授權給{Account.RAP['email']}!"
raise Exception(errMsg)
if module is None:
#模組名不傳的話,預設獲取所有模組資料
json_list = json_obj['data']['modules']
else:
#模組名傳入,獲取對應的模組資料
json_list = jsonpath(json_obj, f"$.data.modules[?(@.name=='{module}')]")
#校驗傳入的模組名是否存在
if not json_list:
raise Exception(f"{module}模組名不存在")
# 介面文件標題名,作為後續的檔名
file_name = json_obj.get('data').get('name')
#對標題名特殊處理
special_str = r"[\/\\\:\*\?\"\<\>\|]"
file_name = re.sub(special_str, "-", file_name)
data = []
#遍歷模組資料
for i in json_list:
modules_data = {}
#模組名
modules_data['modules'] = i['name']
#模組描述
modules_data['description'] = i['description']
interfaces = []
#遍歷interfaces介面資料
for i, dto in enumerate(i['interfaces']):
cases_data = {}
#介面id
cases_data['api_id'] = i + 1
#介面名
cases_data['title'] = dto['name']
#介面描述
cases_data['description'] = dto['description']
#介面路徑
cases_data['url'] = dto['url']
#介面請求方法
cases_data['method'] = dto['method']
#獲取介面的入參和出參
properties_list = jsonpath(dto['properties'], f"$.[?(@.scope=='request')]")
#介面請求頭資料
cases_data['headerData'] = cls.parent_data(properties_list)[2]
#介面query引數
cases_data['queryData'] = cls.parent_data(properties_list)[1]
#介面body引數
cases_data['data'] = cls.parent_data(properties_list)[0]
interfaces.append(cases_data)
modules_data['cases_data'] = interfaces
data.append(modules_data)
return data, file_name
組裝引數
@classmethod
def join_data(cls, json_data, properties, name, type, value, parentId, api_id):
"""
組裝引數
:param json_data: 字典值(存資料用)
:param properties: 介面的入參和出引數據
:param name: 介面名
:param type: 欄位型別
:param value: 欄位值
:param parentId: 父id
:param api_id: 所有的引數id
:return: json_data
"""
#特殊字元替換
name = name.replace(".","")
#沒有父id,直接塞進json_data
if parentId == -1:
v = cls.change_value(type, value)
json_data[name] = v
#有父id且父id在api_id中
elif parentId != -1 and parentId in api_id:
#根據父id獲取父id的資料
parent_dto = jsonpath(properties, f"$.[?(@.id=={parentId})]")
if not parent_dto:
raise Exception("介面文件維護有誤")
parent_dto = parent_dto[0]
#如果父的型別為陣列
if parent_dto['type'] == 'Array':
#找到父的key
parent_array = cls.search_value(json_data, parent_dto['name'])
v = cls.change_value(type, value)
#將子資料掛載在父下面
parent_array[0][name] = v
# 如果父的型別為物件
elif parent_dto['type'] == 'Object':
# 找到父的key
parent_object = cls.search_value(json_data, parent_dto['name'])
v = cls.change_value(type, value)
# 將子資料掛載在父下面
parent_object[name] = v
else:
raise Exception("父資料型別不支援")
else:
pass
# raise Exception("父資料型別不支援")
return json_data
遞迴找對應的 key 資料
@classmethod
def search_value(cls, data, key):
"""
遞迴找到所在key的資料
:param data: 資料
:param key: 需要找的key
:return:
"""
key = key.replace(".", "")
json_data = JsonSearch(object=data)
path = json_data.search_first_path(key)
path_str = cls.path_str(path)
value = jsonpath(data, path_str)[0]
return value
解析後資料展示

專案地址:https://github.com/JokerChat/ApiDocParse
後續擴充套件
- 將資料生成 Excel 格式的介面自動化用例
- 將資料生成 yaml 格式介面自動化用例
- 將資料生成生成 jmeter 指令碼 (jmx)
- 基於上述功能,做成前端頁面,供其他人使用