如何通过Python程序化访问HTTP Toolkit捕获的数据包?
程序化处理HTTP Toolkit拦截数据包的方案
当然可以用Python处理HTTP Toolkit拦截到的数据包,它提供了公开的API支持,也能直接导出/解析HAR格式数据,以下是具体实现方式:
1. 使用HTTP Toolkit公开REST API
HTTP Toolkit内置了REST API,默认关闭,需要先在设置中开启:打开HTTP Toolkit的「Settings」>「API」面板,勾选启用API,默认地址为http://localhost:8000。
获取数据包(JSON/HAR格式)
用Python的requests库直接调用API端点:
import requests API_BASE = "http://localhost:8000" # 获取所有拦截请求的JSON数据 resp = requests.get(f"{API_BASE}/requests") intercepted_requests = resp.json() # 导出所有数据为HAR文件 har_resp = requests.get(f"{API_BASE}/export/har") with open("intercepted_traffic.har", "wb") as f: f.write(har_resp.content)
实时监听新数据包
如果需要实时接收拦截到的新请求,可以通过WebSocket端点ws://localhost:8000/ws监听,用websockets库实现:
import asyncio import websockets async def monitor_traffic(): async with websockets.connect("ws://localhost:8000/ws") as ws: while True: packet = await ws.recv() # 处理实时收到的JSON格式数据包 print("New intercepted packet:", packet) asyncio.run(monitor_traffic())
API的完整文档可以在启用后访问http://localhost:8000/docs查看,支持按请求方法、URL过滤,获取请求/响应详情等操作。
2. 离线解析HAR文件
如果不需要实时处理,也可以直接从HTTP Toolkit界面导出HAR文件,再用Python的haralyzer库解析:
from haralyzer import HarParser # 读取本地HAR文件 with open("intercepted_traffic.har", "r", encoding="utf-8") as f: har_content = f.read() parser = HarParser(har_content) # 遍历所有请求条目 for entry in parser.har_data["entries"]: print(f"请求URL: {entry['request']['url']}") print(f"响应状态码: {entry['response']['status']}")
内容的提问来源于stack exchange,提问作者SpiderPigXL
相关产品推荐
相关产品推荐

