如何在 `requests` 库中设置和使用代理服务器?请写出完整的代码,并说明代理服务器在爬虫中的作用。

在 requests 库中设置和使用代理服务器非常简单,主要通过在请求时传递 proxies 参数来完成。代理服务器在网络爬虫中起到隐藏真实 IP、绕过访问限制以及提高请求成功率的作用。以下是详细的代码示例和说明:

import requests

# 定义代理服务器
proxies = {
    'http': 'http://10.10.1.10:3128',  # HTTP 代理
    'https': 'http://10.10.1.10:1080',  # HTTPS 代理
}

# 使用代理发送请求
try:
    response = requests.get('http://example.com', proxies=proxies, timeout=5)
    print(response.status_code)  # 打印状态码
    print(response.text)  # 打印响应内容
except requests.exceptions.RequestException as e:
    print(f"请求失败: {e}")

详细说明

  1. 代理服务器的作用

    • 隐藏真实 IP:代理服务器可以隐藏爬虫的真实 IP 地址,防止目标网站封禁或追踪。
    • 绕过访问限制:某些网站会对同一 IP 的频繁请求进行限制,使用代理可以绕过这些限制。
    • 提高请求成功率:通过轮换多个代理 IP,可以分散请求压力,提高爬虫的稳定性和成功率。
  2. 代理的类型

    • HTTP 代理:适用于 HTTP 协议的请求。
    • HTTPS 代理:适用于 HTTPS 协议的请求。
    • SOCKS 代理:支持多种协议的代理,需要在 requests 中额外安装 socks 库。
  3. 代理的认证 如果代理服务器需要用户名和密码认证,可以在代理 URL 中添加认证信息:

    proxies = {
        'http': 'http://username:password@10.10.1.10:3128',
        'https': 'http://username:password@10.10.1.10:1080',
    }
    
  4. SOCKS 代理示例 使用 SOCKS 代理需要安装 requests[socks] 或 PySocks 库:

    import requests
    
    proxies = {
        'http': 'socks5://10.10.1.10:1080',
        'https': 'socks5://10.10.1.10:1080',
    }
    
    response = requests.get('http://example.com', proxies=proxies)
    print(response.text)
    
  5. 代理池的使用 在实际爬虫中,通常会使用代理池来动态切换代理 IP,以下是一个简单的代理池示例:

    import random
    
    proxy_list = [
        'http://10.10.1.10:3128',
        'http://10.10.1.11:3128',
        'http://10.10.1.12:3128',
    ]
    
    def get_random_proxy():
        return random.choice(proxy_list)
    
    proxy = get_random_proxy()
    proxies = {
        'http': proxy,
        'https': proxy,
    }
    
    response = requests.get('http://example.com', proxies=proxies)
    print(response.text)
    
  6. 异常处理 代理可能会因为网络问题或代理服务器失效导致请求失败,因此需要捕获异常:

    try:
        response = requests.get('http://example.com', proxies=proxies, timeout=5)
        response.raise_for_status()  # 检查请求是否成功
    except requests.exceptions.RequestException as e:
        print(f"代理请求失败: {e}")
    

总结

通过 requests 库设置代理服务器非常简单,只需在请求时传递 proxies 参数即可。代理服务器在爬虫中起到了保护真实 IP、绕过限制和提高成功率的作用。在实际项目中,建议使用代理池来动态切换代理 IP,并结合异常处理机制来提高爬虫的健壮性。