基于Python的反向代理工具

本文主要介绍通过拦截并修改目标网站的 HTTP 响应内容,实现文字替换功能。结合反向代理技术和 HTML 内容解析,支持动态替换网页中的文本、链接等内容。


工具设计思路

  1. 反向代理架构:拦截客户端请求并转发到目标网站,获取响应后修改内容再返回给客户端。

  2. 内容替换逻辑:使用BeautifulSoup解析 HTML,根据预设规则替换文本或属性。

  3. 动态代理支持:通过 Flask 或http.server实现轻量级代理服务。


完整代码实现

from flask import Flask, request, Response
import requests
from bs4 import BeautifulSoup
from urllib.parse import urlparse

app = Flask(__name__)

# 替换规则字典(可扩展)
REPLACE_RULES = {
    "原始文本1": "替换文本1",
    "原始链接1": "替换链接1",
    # 添加更多规则...
}

def modify_html_content(html):
    """解析并替换HTML内容"""
    soup = BeautifulSoup(html, 'lxml')
    
    # 替换文本内容
    for text in soup.find_all(text=True):
        for old, new in REPLACE_RULES.items():
            if old in text:
                text.replace_with(text.replace(old, new))
    
    # 替换链接属性(如href/src)
    for tag in soup.find_all(['a', 'img', 'script']):
        for attr in ['href', 'src']:
            if tag.get(attr):
                for old, new in REPLACE_RULES.items():
                    if old in tag[attr]:
                        tag[attr] = tag[attr].replace(old, new)
    
    return str(soup)

@app.route('/', defaults={'path': ''})
@app.route('/<path:path>', methods=['GET', 'POST'])
def proxy(path):
    # 目标网站地址(需修改为实际目标)
    target_url = f'https://目标网站.com/{path}'
    
    # 转发请求到目标网站
    headers = {k: v for k, v in request.headers if k != 'Host'}
    if request.method == 'GET':
        resp = requests.get(target_url, headers=headers, params=request.args)
    elif request.method == 'POST':
        resp = requests.post(target_url, headers=headers, data=request.form)
    else:
        return "Method not supported", 405
    
    # 修改响应内容
    if 'text/html' in resp.headers.get('Content-Type', ''):
        modified_content = modify_html_content(resp.text)
        return Response(modified_content, resp.status_code, resp.headers.items())
    else:
        return Response(resp.content, resp.status_code, resp.headers.items())

if __name__ == '__main__':
    app.run(host='0.0.0.0', port=5000, debug=True)

核心功能说明

  1. 反向代理服务

    • 使用 Flask 接收客户端请求,转发到目标网站并获取响应。

    • 支持所有 HTTP 方法(GET/POST 等),保留原始请求头和参数。

  2. 内容替换引擎

    • 通过BeautifulSoup解析 HTML,遍历文本节点和标签属性。

    • 根据REPLACE_RULES字典动态替换内容,支持文本和链接修改。

  3. 动态内容处理

    • 仅修改 HTML 响应,其他类型(如图片 /CSS)直接透传。

    • 保留原始响应状态码和头信息(如 Cookie/ 缓存控制)。


使用步骤

  1. 安装依赖

    pip install flask requests beautifulsoup4 lxml
  2. 配置规则

    • 修改REPLACE_RULES字典,定义需要替换的文本和链接。

  3. 启动代理

    python proxy.py
    • 访问http://localhost:5000即可看到修改后的网站。

  4. 高级配置(可选):

    • HTTPS 支持:使用mitmproxy拦截 HTTPS 流量并安装证书。

    • 性能优化:引入缓存(如Redis)减少重复解析开销。


应用场景

  • 本地开发调试:临时修改线上页面样式或文案进行测试。

  • 内容定制化:为特定用户群体展示差异化内容。

  • 教育演示:快速创建教学用例(如修改新闻标题)。


注意事项

  1. 合法性:确保遵守目标网站的robots.txt和服务条款,避免法律风险。

  2. 性能影响:解析大文件可能增加延迟,建议限制处理范围。

  3. 动态内容:对 JavaScript 渲染的内容无效,需结合 Selenium。

如需更复杂的功能(如正则替换、XPath 定位),可扩展modify_html_content方法。


基于Python的反向代理工具
https://uniomo.com/archives/ji-yu-pythonde-fan-xiang-dai-li-gong-ju
作者
雨落秋垣
发布于
2025年10月20日
许可协议