Python2.7简单代理

2024-06-17 12:54:22 发布

您现在位置:Python中文网/ 问答频道 /正文

我想用python制作一个简单的代理服务器 这就是它需要做的: -从客户端获取url -获取该url的内容 -操纵网站上的每一个链接 -将被操纵的站点返回给用户

到目前为止,我所做的唯一一件事(使用urllib或requests)是对所需url的简单重定向 这意味着我甚至不能将我持有的响应对象返回给用户

有什么办法吗?在

到目前为止我掌握的代码是:

import BaseHTTPServer
import requests
from urlparse import urlparse
import HTTPClient


PORT = 443


class Proxy(BaseHTTPServer.BaseHTTPRequestHandler):
    def do_HEAD(self):
        query = urlparse(self.path).query
        query_components = dict(qc.split("=") for qc in query.split("?"))
        new_url = query_components['url']
        r = requests.get(url, stream=True)
        self.send_response(301)
        #self.send_header('Location', new_url)
        self.send_header("Content-type", "text/html")
        self.end_headers()
        self.wfile.write(r.content)
    def do_GET(self):
        query = urlparse(self.path).query
        query_components = dict(qc.split("=") for qc in query.split("?"))
        if query_components['url'].find('http://') != 0:
            self.send_error(400, "Bad Url - Http Required")
        else:
            self.do_HEAD()



try:
    httpd = BaseHTTPServer.HTTPServer(('localhost', PORT), Proxy)
    print "Serving at port", PORT
    httpd.serve_forever()
except keyboardInterrupt:
    httpd.server_close()
    print "Closing Server"

我甚至试图以某种方式返回“r”(实际的响应对象),但没有成功

注释中的行用于简单的重定向,甚至不需要保存站点的内容

非常感谢


Tags: importselfsendurl内容portcomponentsquery
1条回答
网友
1楼 · 发布于 2024-06-17 12:54:22

这在linux上应该可以工作,希望它能给您一个起点。在

import SocketServer
import SimpleHTTPServer
import urllib

PORT = 1234

class Proxy(SimpleHTTPServer.SimpleHTTPRequestHandler):
    def do_GET(self):
        self.copyfile(urllib.urlopen(self.path), self.wfile)

httpd = SocketServer.ForkingTCPServer(('', PORT), Proxy)
print "serving at port", PORT
httpd.serve_forever()

相关问题 更多 >