
爬虫自动换代理IP的逻辑特别简单:准备一批可用代理IP → 每次请求随机挑一个用 → 自动检测IP能不能用 → 删掉失效IP、补充新IP。全程自动化,不用手动干预。
这套模板自带4个超实用核心能力:
代码只需要requests库,直接复制下面命令安装就行,其他都是Python自带无需额外安装:
pip install requests这套代码配齐了代理校验、自动换IP、失败重试、无效IP清理所有功能,改下配置就能直接用,新手也能快速上手。
import requests
import random
import time
# ====================== 自定义配置区(只改这里就够了)======================
# 1. 静态代理IP池(格式统一为 http://IP:端口,可批量替换成自己的代理)
PROXY_POOL = [
"http://113.120.36.122:8080",
"http://120.79.14.113:8080",
"http://119.29.155.99:8080",
"http://106.55.200.138:8080"
]
# 2. 动态代理API(用付费代理就填地址,不用直接留空即可)
PROXY_API_URL = ""
# 3. 爬虫请求基础设置
TIMEOUT = 10 # 请求超时时间,超过10秒直接判定失败
RETRY_TIMES = 3 # 请求失败最多重试3次
TEST_URL = "https://httpbin.org/ip" # 校验代理的测试接口,可通用
HEADERS = {
"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36"
}
# =================================================================
# 实时更新的可用代理池,自动剔除坏IP
usable_proxies = PROXY_POOL.copy()
def get_dynamic_proxy():
"""
从付费代理API自动获取新IP
返回:可用的代理IP地址
"""
try:
res = requests.get(PROXY_API_URL, timeout=10)
if res.status_code == 200 and res.text.strip():
proxy_ip = f"http://{res.text.strip()}"
return proxy_ip
except Exception as e:
print(f"动态代理获取失败:{str(e)}")
return None
def check_proxy(proxy):
"""检测单个代理是否能用,有效返回True,失效返回False"""
try:
res = requests.get(
url=TEST_URL,
proxies={"http": proxy, "https": proxy},
headers=HEADERS,
timeout=TIMEOUT
)
if res.status_code == 200:
print(f"✅ 代理可用:{proxy},当前访问IP:{res.json().get('origin')}")
return True
except Exception as e:
print(f"❌ 代理失效:{proxy}")
return False
def get_random_proxy():
"""随机获取一个可用代理,自动清理无效IP、补全新IP"""
global usable_proxies
# 代理池空了就尝试更新
if not usable_proxies:
print("⚠️ 代理池已用完,正在尝试更新代理...")
if PROXY_API_URL:
new_proxy = get_dynamic_proxy()
if new_proxy and check_proxy(new_proxy):
usable_proxies.append(new_proxy)
# 还是没有可用IP就抛出异常
if not usable_proxies:
raise Exception("没有可用代理了!请补充IP或检查代理API")
# 循环筛选有效代理
while True:
proxy = random.choice(usable_proxies)
if check_proxy(proxy):
return proxy
else:
usable_proxies.remove(proxy)
if not usable_proxies:
raise Exception("所有代理均已失效,请更新IP池")
def proxy_spider_request(url, method="get", data=None, params=None):
"""
爬虫通用请求函数,自动换IP+失败重试
:param url: 要爬的链接
:param method: 请求方式 get/post
:param data: post请求参数
:param params: get请求参数
:return: 响应对象
"""
# 循环重试请求
for i in range(RETRY_TIMES):
try:
proxy = get_random_proxy()
proxies = {"http": proxy, "https": proxy}
print(f"\n第{i+1}次请求,本次使用代理:{proxy}")
# 区分GET/POST请求
if method.lower() == "get":
res = requests.get(
url=url,
headers=HEADERS,
proxies=proxies,
params=params,
timeout=TIMEOUT
)
else:
res = requests.post(
url=url,
headers=HEADERS,
proxies=proxies,
data=data,
timeout=TIMEOUT
)
# 请求成功直接返回结果
if res.status_code in [200, 201, 202]:
print("🎉 请求成功!")
return res
else:
print(f"⚠️ 状态码异常:{res.status_code},即将换IP重试")
time.sleep(1)
continue
except Exception as e:
print(f"❌ 请求失败,换代理重试中...")
time.sleep(1)
continue
print(f"❌ 已重试{RETRY_TIMES}次,请求失败,跳过当前链接")
return None
# 测试运行:验证自动换IP效果
if __name__ == "__main__":
test_url = "https://httpbin.org/ip"
# 连续5次请求,观察IP切换效果
for i in range(5):
response = proxy_spider_request(test_url)
if response:
print("当前请求IP结果:", response.json())
time.sleep(2)适配两种主流使用场景,按需选择就行:
通过公开的IP检测接口精准校验代理状态,能快速筛掉超时、封禁、无法连接的无效IP,避免做无用请求,节省爬虫资源。
每一次网络请求都会随机挑选可用IP,遇到超时、连接失败、状态码异常等问题,会自动换新IP重试,不用手动调试,大幅降低爬虫翻车概率。
替换成你自己的代理API地址,就能自动批量获取新IP,不用手动更新IP池:
# 短效API示例(替换自己的订单号和密钥即可)
PROXY_API_URL = "https://zdaye.com/api/getdps/?orderid=xxxxxx&num=1&pt=1&sep=1"time.sleep(random.uniform(1, 3)),模拟真人浏览节奏原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。
如有侵权,请联系 cloudcommunity@tencent.com 删除。
原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。
如有侵权,请联系 cloudcommunity@tencent.com 删除。