在进行Python爬虫开发时,我们经常会使用requests库来发送HTTP请求。然而,在配置代理服务器或者使用某些特定的网络环境时,我们可能会遇到requests.exceptions.ProxyError: HTTPSConnectionPool这样的报错。这个问题通常发生在尝试通过代理服务器访问HTTPS资源时,表明爬虫在与代理服务器建立连接时遇到了问题。
以下是一个可能导致requests.exceptions.ProxyError: HTTPSConnectionPool错误的代码示例:
import requests
proxies = {
'https': 'https://incorrect_proxy_address:port', # 错误的代理地址和端口
}
try:
response = requests.get('https://example.com', proxies=proxies)
print(response.text)
except requests.exceptions.ProxyError as e:
print(f"ProxyError occurred: {e}")
在这段代码中,如果代理服务器的地址或端口配置错误,或者代理服务器无法正常工作,就会触发ProxyError。
为了解决这个问题,我们需要确保代理服务器的配置是正确的,并且代理服务器是可用的。以下是一个修正后的代码示例:
import requests
proxies = {
'https': 'https://correct_proxy_address:port', # 正确的代理地址和端口
# 如果代理需要认证,可以添加认证信息,例如:
# 'https': 'http://user:password@correct_proxy_address:port',
}
headers = {
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/99.0.4844.51 Safari/537.36',
} # 设置合适的User-Agent有助于避免被目标网站拦截
timeout = 10 # 设置请求超时时间,避免无限等待
try:
response = requests.get('https://example.com', proxies=proxies, headers=headers, timeout=timeout)
print(response.text)
except requests.exceptions.ProxyError as e:
print(f"ProxyError occurred: {e}")
在这段代码中,我们修正了代理服务器的配置,并添加了请求头和超时设置,以增加请求的健壮性。