需要帮助编写扭曲的代理

时间:2011-06-27 11:10:07

标签: 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()
你能帮帮我吗?我很欣赏一个简单的例子(例如在身体上添加一些东西......)。

1 个答案:

答案 0 :(得分:6)

我所做的是实现一个新的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

希望这也适合你。