首页 / 用例 / 轮换代理
免费轮换代理池
轮换代理让每个请求从不同 IP 发出。你不必买付费服务——用一个免费、每小时验证的列表就能自建代理池。下面是内置刷新与重试的实现模式。
轮换模式
三个部分:加载一个验证过的池,每次调用轮换到下一个代理,并按定时器刷新池子以替换失效代理。
import itertools, time, requests
LIST = "https://raw.githubusercontent.com/xyzs996/free-proxy-health-list/main/proxies/all/data.json"
def load_pool():
data = requests.get(LIST, timeout=15).json()
def to_url(p):
proto, hp = p["protocol"], p["proxy"]
if proto.startswith("socks5"): return f"socks5h://{hp}"
if proto.startswith("socks4"): return f"socks4://{hp}"
return f"http://{hp}"
return [to_url(p) for p in data]
pool = load_pool()
cycle = itertools.cycle(pool)
refreshed = time.time()
def get(url, tries=10):
global pool, cycle, refreshed
if time.time() - refreshed > 1800: # 每 30 分钟刷新
pool = load_pool(); cycle = itertools.cycle(pool); refreshed = time.time()
for _ in range(tries):
px = next(cycle) # 轮换到下一个 IP
try:
r = requests.get(url, proxies={"http": px, "https": px}, timeout=8)
if r.ok: return r
except requests.RequestException:
continue # 失效就继续轮换
raise RuntimeError("这一轮没有可用代理")
print(get("https://httpbin.org/ip").json())
让代理池更健康的技巧
从 fast 或 top-1000 子集起步命中率更高;连续失败两次的代理直接丢弃;成功率下降就更频繁刷新。列表每小时重新验证,随时可拉到新的。
常见问题
能自己搭免费轮换代理吗?
能——轮换一个验证过的列表并在失败时重试下一条。轮换+重试正是让免费代理可用的关键。
多久刷新一次代理池?
每 15–60 分钟都行。源列表每小时做健康检测并重新发布。
什么时候该改用付费?
如果你需要一个稳定的轮换 URL、带 SLA、且不想自己处理失效代理,付费端点值得。规划中的 Pro API 正是提供这个。