from mitmproxy import http from mitmproxy.tools.main import mitmdump class AddHeader: def __init__(self): self.num = 0 def request(self, flow: http.HTTPFlow) -> None: self.num += 1 flow.request.headers["My-Header"] = f"Request {self.num}" print("Request Headers: ") for name, value in flow.request.headers.items(): print(f"{name}: {value}") def response(self, flow: http.HTTPFlow) -> None: self.num += 1 flow.response.headers["My-Header"] = f"Response {self.num}" print("Response Headers: ") for name, value in flow.response.headers.items(): print(f"{name}: {value}") addons = [ AddHeader() ] if __name__ == "__main__": mitmdump(['-p', '8081', '-s', __file__]) 我使用以上代码进行抓包,我如何才能将抓取到的内容保存到本地,请帮我完善代码,我需要保存的是request而不是response
时间: 2024-03-09 12:50:29 浏览: 99
解决H5py的DLL问题:from . import h5 as _h5
3星 · 编辑精心推荐
你可以使用Python中的`requests`库来将抓取到的内容保存到本地文件中。在AddHeader类中,在`request`方法中添加以下代码即可将抓取到的request内容保存到本地文件中:
```python
import requests
def save_request(flow: http.HTTPFlow):
with open(f"request_{self.num}.txt", "w") as f:
f.write(f"{flow.request.method} {flow.request.url}\n")
for name, value in flow.request.headers.items():
f.write(f"{name}: {value}\n")
f.write("\n")
if flow.request.method == "POST":
f.write(flow.request.content.decode("utf-8"))
class AddHeader:
def __init__(self):
self.num = 0
def request(self, flow: http.HTTPFlow) -> None:
self.num += 1
flow.request.headers["My-Header"] = f"Request {self.num}"
print("Request Headers: ")
for name, value in flow.request.headers.items():
print(f"{name}: {value}")
save_request(flow)
def response(self, flow: http.HTTPFlow) -> None:
self.num += 1
flow.response.headers["My-Header"] = f"Response {self.num}"
print("Response Headers: ")
for name, value in flow.response.headers.items():
print(f"{name}: {value}")
addons = [
AddHeader()
]
if __name__ == "__main__":
mitmdump(['-p', '8081', '-s', __file__])
```
在以上代码中,`save_request`方法会将抓取到的request内容以文本形式保存到以`request_序号.txt`命名的文件中。其中,`序号`为请求的序号,即第几个请求。如果请求是POST方法,则会将请求的content也保存到文件中。
阅读全文