python - 需要帮助编写一个扭曲的代理

标签 python proxy twisted

我想编写一个简单的代理来打乱所请求页面正文中的文本。我已经在 stackoverflow 上阅读了部分扭曲的文档和其他一些类似的问题,但我有点菜鸟,所以我还是不明白。

我现在就是这样,不知道怎么访问和修改页面

from twisted.web import proxy, http
from twisted.internet import protocol, reactor
from twisted.python import log
import sys

log.startLogging(sys.stdout)

class ProxyProtocol(http.HTTPChannel):
   requestFactory = PageHandler

class ProxyFactory(http.HTTPFactory):
   protocol = ProxyProtocol

if __name__ == '__main__':
   reactor.listenTCP(8080, ProxyFactory())
   reactor.run()

你能帮帮我吗?我会很感激一个简单的例子(例如,向 body 添加一些东西等......)。

最佳答案

我所做的是实现一个新的 ProxyClient,在我从网络服务器下载数据之后,在将数据发送到网络浏览器之前,我会在其中修改数据。

from twisted.web import proxy, http
class MyProxyClient(proxy.ProxyClient):
 def __init__(self,*args,**kwargs):
  self.buffer = ""
  proxy.ProxyClient.__init__(self,*args,**kwargs)
 def handleResponsePart(self, buffer):
  # Here you will get the data retrieved from the web server
  # In this example, we will buffer the page while we shuffle it.
  self.buffer = buffer + self.buffer
 def handleResponseEnd(self):
  if not self._finished:
   # We might have increased or decreased the page size. Since we have not written
   # to the client yet, we can still modify the headers.
   self.father.responseHeaders.setRawHeaders("content-length", [len(self.buffer)])
   self.father.write(self.buffer)
  proxy.ProxyClient.handleResponseEnd(self)

class MyProxyClientFactory(proxy.ProxyClientFactory):
 protocol = MyProxyClient

class ProxyRequest(proxy.ProxyRequest):
 protocols = {'http': MyProxyClientFactory}
 ports = {'http': 80 }
 def process(self):
  proxy.ProxyRequest.process(self)

class MyProxy(http.HTTPChannel):
 requestFactory = ProxyRequest

class ProxyFactory(http.HTTPFactory):
 protocol = MyProxy

希望这对你也有用。

关于python - 需要帮助编写一个扭曲的代理,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6491932/

相关文章:

Python:将驼峰大小写转换为使用正则表达式分隔的空格并考虑首字母缩略词

python - 如何在 FastAPI 中对模型的所有字段启用过滤

Python3 请求不使用传入代理

node.js - 接受 SSL 流量的 Node http 代理端口号

networking - twisted .loseConnection 不会立即失去连接?

python - Twisted:使代码非阻塞

Python编译/解释过程

python - Python 包是否可以依赖于另一个 Python 包的特定版本控制修订版?

node.js - Angular 通用代理

python - twisted:一个客户端,多个服务器