142 lines
3.8 KiB
Python
142 lines
3.8 KiB
Python
"""
|
||
Python中设置代理的完整示例
|
||
"""
|
||
|
||
import os
|
||
import requests
|
||
import urllib.request
|
||
from urllib.parse import urlparse
|
||
|
||
|
||
def set_global_proxy(proxy_url):
|
||
"""
|
||
为整个Python进程设置全局代理
|
||
|
||
Args:
|
||
proxy_url (str): 代理地址,例如 "http://proxy.example.com:8080"
|
||
或 "socks5://127.0.0.1:1080"
|
||
"""
|
||
# 解析代理URL
|
||
parsed = urlparse(proxy_url)
|
||
proxy_address = f"{parsed.scheme}://{parsed.hostname}:{parsed.port}"
|
||
|
||
# 设置环境变量(影响urllib、requests等库)
|
||
os.environ['http_proxy'] = proxy_address
|
||
os.environ['https_proxy'] = proxy_address
|
||
|
||
# 有些库可能使用大写环境变量
|
||
os.environ['HTTP_PROXY'] = proxy_address
|
||
os.environ['HTTPS_PROXY'] = proxy_address
|
||
|
||
print(f"已设置全局代理: {proxy_address}")
|
||
|
||
|
||
def set_requests_proxy(proxy_url, username=None, password=None):
|
||
"""
|
||
仅为requests库设置代理
|
||
|
||
Args:
|
||
proxy_url (str): 代理地址
|
||
username (str, optional): 代理用户名
|
||
password (str, optional): 代理密码
|
||
|
||
Returns:
|
||
dict: 可直接用于requests的代理字典
|
||
"""
|
||
if username and password:
|
||
# 添加认证信息
|
||
parsed = urlparse(proxy_url)
|
||
proxy_with_auth = f"{parsed.scheme}://{username}:{password}@{parsed.hostname}:{parsed.port}"
|
||
proxies = {
|
||
'http': proxy_with_auth,
|
||
'https': proxy_with_auth
|
||
}
|
||
else:
|
||
proxies = {
|
||
'http': proxy_url,
|
||
'https': proxy_url
|
||
}
|
||
|
||
print(f"已为requests设置代理: {proxy_url}")
|
||
return proxies
|
||
|
||
|
||
def test_proxy_connection(test_url="https://httpbin.org/ip", proxies=None):
|
||
"""
|
||
测试代理连接
|
||
|
||
Args:
|
||
test_url (str): 测试URL
|
||
proxies (dict, optional): 代理设置
|
||
"""
|
||
try:
|
||
if proxies:
|
||
response = requests.get(test_url, proxies=proxies, timeout=10)
|
||
else:
|
||
response = requests.get(test_url, timeout=10)
|
||
|
||
print(f"代理测试成功,IP信息: {response.json()}")
|
||
return True
|
||
except Exception as e:
|
||
print(f"代理测试失败: {e}")
|
||
return False
|
||
|
||
|
||
def clear_proxy():
|
||
"""
|
||
清除代理设置
|
||
"""
|
||
for var in ['http_proxy', 'https_proxy', 'HTTP_PROXY', 'HTTPS_PROXY']:
|
||
if var in os.environ:
|
||
del os.environ[var]
|
||
|
||
print("已清除代理设置")
|
||
|
||
|
||
def example_with_requests():
|
||
"""
|
||
使用requests库通过代理访问网络的示例
|
||
"""
|
||
print("\n=== Requests代理示例 ===")
|
||
|
||
# 不使用代理
|
||
print("不使用代理:")
|
||
test_proxy_connection()
|
||
|
||
# 使用代理(示例地址,请替换为实际代理地址)
|
||
print("\n使用代理:")
|
||
proxies = set_requests_proxy("http://proxy.example.com:8080")
|
||
# test_proxy_connection(proxies=proxies) # 取消注释并替换为实际代理地址进行测试
|
||
|
||
|
||
def example_with_global_proxy():
|
||
"""
|
||
设置全局代理的示例
|
||
"""
|
||
print("\n=== 全局代理示例 ===")
|
||
|
||
# 设置全局代理
|
||
set_global_proxy("http://proxy.example.com:8080")
|
||
|
||
# 测试连接
|
||
test_proxy_connection()
|
||
|
||
# 清除代理
|
||
clear_proxy()
|
||
|
||
|
||
if __name__ == "__main__":
|
||
print("Python代理设置完整示例")
|
||
print("=" * 40)
|
||
|
||
# 示例1: 使用requests设置代理
|
||
example_with_requests()
|
||
|
||
# 示例2: 设置全局代理
|
||
example_with_global_proxy()
|
||
|
||
print("\n代理设置说明:")
|
||
print("1. 环境变量方法影响整个Python进程")
|
||
print("2. requests代理方法仅影响使用requests的请求")
|
||
print("3. 实际使用时请替换示例代理地址为真实地址")
|
||
print("4. SOCKS代理需要安装: pip install requests[socks]") |