Python requests库配置HTTP代理指南
华科动态小孙
2025年07月02日 16:45

requests库是Python中最流行的HTTP请求库之一,它提供了简单易用的API来发送HTTP请求。在实际应用中,我们经常需要通过代理服务器发送请求,以实现访问控制、匿名浏览或爬虫开发等目的。本文将详细介绍如何使用requests库配置HTTP代理。

基本代理配置

requests库通过proxies参数支持HTTP代理配置,基本用法如下:

python

 

import requests

 

 

 

proxies = {

 

'http': 'http://10.10.1.10:3128',

 

'https': 'http://10.10.1.10:1080',

 

}

 

 

 

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

 

print(response.text)

代理认证

如果代理服务器需要认证,可以在代理URL中包含用户名和密码:

python

 

proxies = {

 

'http': 'http://username:password@10.10.1.10:3128/',

 

'https': 'http://username:password@10.10.1.10:1080/',

 

}

 

 

 

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

或者使用HTTPProxyAuth进行更安全的认证:

python

 

from requests.auth import HTTPProxyAuth

 

 

 

proxies = {

 

'http': 'http://10.10.1.10:3128',

 

'https': 'http://10.10.1.10:1080',

 

}

 

auth = HTTPProxyAuth('username', 'password')

 

 

 

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

SOCKS代理支持

requests库本身不支持SOCKS代理,但可以通过安装requests[socks]额外包来实现:

bash

 

pip install requests[socks]

然后配置SOCKS代理:

python

 

proxies = {

 

'http': 'socks5://user:pass@host:port',

 

'https': 'socks5://user:pass@host:port'

 

}

 

 

 

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

环境变量配置

requests库会自动读取HTTP_PROXY和HTTPS_PROXY环境变量:

python

 

import os

 

os.environ['HTTP_PROXY'] = 'http://10.10.1.10:3128'

 

os.environ['HTTPS_PROXY'] = 'http://10.10.1.10:1080'

 

 

 

# 现在所有请求都会自动使用代理

 

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

会话级代理配置

对于需要多次请求的情况,可以使用Session对象配置代理:

python

 

session = requests.Session()

 

session.proxies = proxies

 

 

 

response1 = session.get('http://example.com')

 

response2 = session.get('http://example.org')

代理池实现

在实际爬虫应用中,我们可能需要使用多个代理来实现轮换:

python

 

import random

 

 

 

proxy_pool = [

 

'http://proxy1:8080',

 

'http://proxy2:8080',

 

'http://proxy3:8080'

 

]

 

 

 

def get_random_proxy():

 

return {'http': random.choice(proxy_pool)}

 

 

 

proxies = get_random_proxy()

 

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

注意事项

1. 代理服务器的稳定性会影响请求成功率,建议实现重试机制

2. 免费代理通常不可靠,考虑使用付费代理服务

3. 注意代理服务器的地理位置,可能影响访问速度

4. 某些网站会检测并阻止代理请求

通过以上方法,您可以灵活地在requests库中配置各种HTTP代理,满足不同的网络访问需求。