在Python中使用代理服务器可以通过多种方式实现,以下是几种常见的方法:
使用 `requests` 库
`requests` 库是一个流行的HTTP库,可以方便地设置代理服务器。
```python
import requests
proxies = {
'http': 'http://10.10.10.1:1234', HTTP代理
'https': 'https://10.10.10.1:1234' HTTPS代理
}
try:
response = requests.get('http://example.com', proxies=proxies, timeout=5)
print(response.status_code)
except requests.exceptions.RequestException as e:
print(f'请求出错: {e}')
使用 `urllib` 库
`urllib` 是Python内置的HTTP请求库,可以通过 `ProxyHandler` 和 `build_opener` 方法设置代理。
```python
import urllib.request
proxy_support = urllib.request.ProxyHandler({'http': 'http://10.10.10.1:1234', 'https': 'https://10.10.10.1:1234'})
opener = urllib.request.build_opener(proxy_support)
urllib.request.install_opener(opener)
content = urllib.request.urlopen('http://example.com').read()
环境变量设置
可以通过设置环境变量来让Python脚本使用代理服务器。
```bash
export http_proxy=http://10.10.10.1:1234
export https_proxy=http://10.10.10.1:1234
创建简单的HTTP代理服务器
可以使用Python的 `socket` 和 `threading` 模块创建一个简单的HTTP代理服务器。
```python
import socket
import threading
class ProxyServer:
def __init__(self, host='127.0.0.1', port=8899):
self.server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
self.server.bind((host, port))
self.server.listen(5)
print(f"代理服务器运行在 {host}:{port}")
def handle_client(self, client_socket):
request = client_socket.recv(4096)
try:
解析HTTP请求的目标主机和端口
first_line = request.split(b'\n')
url = first_line.split()
创建到目标服务器的连接
target_host = url.split(b'://').split('/')
target_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
target_socket.connect((target_host, 80))
转发请求和响应
target_socket.send(request)
except Exception as e:
print(f"转发请求出错: {e}")
finally:
client_socket.close()
启动代理服务器
server = ProxyServer()
server.serve_forever()
使用 `tsocks` 库
`tsocks` 是一个允许在Python中使用SOCKS代理的库。
```bash
pip install tsocks
然后使用 `tsocks` 运行脚本:
```bash
tsocks python3 myscript.py
注意事项
直接使用Python创建的代理服务器可能不适合生产环境,可能不稳定且不安全。
使用代理时一定要设置 `timeout`,避免代理服务器响应太慢而卡住程序。
维护一个代理池,每次随机选择不同的代理使用,可以避免被检测出来。
以上方法可以帮助你在Python中设置和使用代理服务器。