You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何让Python Requests库自动使用V2Ray的PAC代理?

让Requests自动适配V2Ray PAC代理的解决方案

核心思路

通过解析V2Ray的PAC规则文件,对每个请求的目标URL判断是否需要走代理,再动态给Requests设置代理,实现和浏览器一致的自动代理效果。

具体步骤

1. 安装依赖库

需要用到pacparser解析PAC文件的JS规则,配合requests实现请求:

pip install pacparser requests

2. 获取V2Ray的PAC内容

V2Ray通常提供两种PAC获取方式:

  • 本地文件路径:手动导出的PAC文件(如C:\v2ray\autoproxy.pac或~/v2ray/autoproxy.pac)
  • 本地HTTP服务:默认V2Ray会启动PAC服务,地址一般为http://127.0.0.1:10809/pac(端口可在V2Ray客户端设置中查看)

3. 编写自动代理逻辑

以下是完整代码示例,实现URL自动判断代理:

import requests
import pacparser

# 初始化pacparser解析器
pacparser.init()

# 加载PAC规则(二选一)
# 方式1:加载本地PAC文件
# pacparser.parse_pac_file("/path/to/your/autoproxy.pac")
# 方式2:从HTTP服务加载PAC内容
pac_content = requests.get("http://127.0.0.1:10809/pac").text
pacparser.parse_pac_string(pac_content)

# V2Ray代理配置(根据实际设置调整,默认socks5代理为例)
V2RAY_PROXY = {
    "http": "socks5://127.0.0.1:1080",
    "https": "socks5://127.0.0.1:1080"
}

def get_proxies_for_url(url):
    """根据URL判断是否需要使用代理"""
    # 调用PAC规则获取代理策略
    proxy_result = pacparser.find_proxy(url, url.split("/")[2])
    if proxy_result.startswith("PROXY") or proxy_result.startswith("SOCKS"):
        return V2RAY_PROXY
    else:
        # 无需代理,返回空字典
        return {}

# 测试示例
if __name__ == "__main__":
    # 需要代理的站点
    res1 = requests.get("https://google.com", proxies=get_proxies_for_url("https://google.com"))
    print(f"Google请求状态码: {res1.status_code}")
    
    # 无需代理的站点
    res2 = requests.get("https://baidu.com", proxies=get_proxies_for_url("https://baidu.com"))
    print(f"Baidu请求状态码: {res2.status_code}")
    
    # 清理解析器资源
    pacparser.cleanup()

4. 处理PyInstaller打包问题

使用pyinstaller --windowed main.py打包时,需确保pacparser依赖被正确包含:

  • 打包命令添加--hidden-import pacparser参数:
pyinstaller --windowed --hidden-import pacparser main.py
  • 若打包后运行报错,可手动将pacparser的动态链接库(如Windows下的pacparser.dll)复制到打包后的程序目录。

注意事项

  • 确保V2Ray客户端处于运行状态,PAC服务/文件路径正确
  • 若V2Ray使用HTTP代理而非SOCKS5,需修改V2RAY_PROXY中的代理地址(如http://127.0.0.1:10809)
  • 复杂PAC规则需pacparser支持ES5语法,若解析错误可尝试更新pacparser到最新版本

内容的提问来源于stack exchange,提问作者王鹏宇

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.01 23:55:16