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__]) 我使用以上代码进行抓包,我如何才能将抓取到的内容保存到本地,请帮我完善代码
时间: 2024-03-09 15:50:00 浏览: 136
你可以在 `response` 函数中,使用 Python 的文件操作将抓取到的内容保存到本地文件中。下面是修改后的代码:
```python
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}")
# 将抓取到的内容保存到本地文件中
with open('response.txt', 'a') as f:
f.write(flow.response.text)
addons = [
AddHeader()
]
if __name__ == "__main__":
mitmdump(['-p', '8081', '-s', __file__])
```
在 `response` 函数中,我们使用 `with open('response.txt', 'a') as f:` 打开一个名为 `response.txt` 的文件,并设置文件模式为追加模式,这样每次抓取到的内容都会被追加到文件的末尾。然后我们使用 `f.write(flow.response.text)` 将抓取到的内容写入到文件中。最后别忘了关闭文件。
阅读全文