当使用v2ray时,python如何自动请求库使用系统代理(pac是解决的关键)?

问题描述 投票:0回答:1

pac(代理自动配置),如果启用代理我想自动使用它,pac是解决问题的关键。

终端中的python requests请求库不使用系统代理,除非“export http_proxy=http://127.0.0.1:1087;export https_proxy=http://127.0.0.1:1087;export ALL_PROXY=socks5://127.0. 0.1:1080"

现在我已经运行了“pyinstaller --windowed main.py”来打包应用程序,但不自动使用系统代理,

我希望python的requests库自动使用v2ray的代理

它是硬编码的,不太好。我想要的是浏览器效果,浏览器无法通过代理访问访问网站

`

import requests

proxies = {
'http': 'http://proxy.example.com:8080',
'https': 'http://proxy.example.com:8080',
}

response = requests.get('http://example.com', proxies=proxies)`

如何解决?

python-requests proxy
1个回答
0
投票

您可以使用

os
模块来加载代理信息,而不是硬编码。

import os
import requests

# Get proxy server information from environment variables
proxy_host = os.environ.get('HTTP_PROXY')  # or 'http_proxy' depending on your environment
proxy_port = os.environ.get('HTTP_PROXY_PORT')  # or 'http_proxy_port' depending on your environment

# If the proxy server requires authentication, also get the username and password from environment variables
proxy_username = os.environ.get('HTTP_PROXY_USERNAME')
proxy_password = os.environ.get('HTTP_PROXY_PASSWORD')

# Build the proxy dictionary
proxies = {
    'http': f'http://{proxy_username}:{proxy_password}@{proxy_host}:{proxy_port}' if proxy_username and proxy_password else f'http://{proxy_host}:{proxy_port}',
    'https': f'https://{proxy_username}:{proxy_password}@{proxy_host}:{proxy_port}' if proxy_username and proxy_password else f'https://{proxy_host}:{proxy_port}'
}

# Set the target URL
url = 'https://www.example.com'

# Send a GET request through the proxy server to the target URL
response = requests.get(url, proxies=proxies)

# Print the response content
print(response.text)

记住在运行脚本之前设置环境变量:

export HTTP_PROXY="your_proxy_host"
export HTTP_PROXY_PORT="your_proxy_port"
export HTTP_PROXY_USERNAME="your_username"
export HTTP_PROXY_PASSWORD="your_password"
© www.soinside.com 2019 - 2024. All rights reserved.