你可以使用一个循环来不断尝试使用列表中的不同代理,直到获得有效的响应。这里是一个示例代码:
import requests
proxy_list = ['proxy1', 'proxy2', 'proxy3'] # 代理列表
response = None
for proxy in proxy_list:
try:
# 使用代理发送请求
response = requests.get(url, proxies={'http': proxy, 'https': proxy})
if response.status_code == 200:
break # 如果得到有效的响应,跳出循环
except requests.exceptions.RequestException:
continue # 如果请求出错,继续尝试下一个代理
if response is not None:
# 处理有效的响应
print(response.text)
else:
print("无法获得有效的响应")
在这个示例中,我们使用requests
库发送HTTP请求,并将proxies
参数设置为当前循环迭代的代理。如果得到了有效的响应(状态码为200),我们会跳出循环并处理该响应。如果请求出错,我们会继续尝试下一个代理。如果遍历完所有代理后仍然没有得到有效的响应,我们会输出一条错误信息。
请确保在使用之前安装了requests
库(可以通过pip install requests
命令安装)。