Code2025

代理 IP 使用:同一个接口,为什么换个地址就能继续抓

写于 2026-11-15·更新于 2026-11-15·3905 字·4 段可运行·11 条反链
本页目录

问题从哪来#

课堂示例1 只有三行核心:

python
proxy = {'https': '49.69.37.165:40023'}response = requests.get('https://myip.ipip.net', headers=headers, proxies=proxy, timeout=3)print(response.text)

myip.ipip.net 是个「回声墙」:它把你出口 IP 的归属地原样告诉你。不走代理时它报你家宽带地址,走代理时它报代理的地址——这是验证代理是否生效的唯一可靠办法,比看请求是否成功严谨得多。

第一步:proxies 字典的结构与两个坑#

python
ip = "123.181.235.47:40010"proxy_class = {"https": ip}          # 课堂写法:只给 https 键print("访问 https 站点走代理吗:", "https" in proxy_class)print("访问 http  站点走代理吗:", "http" in proxy_class, "<- 这时会裸奔用真 IP!") proxy_full = {"http": f"http://{ip}", "https": f"http://{ip}"}print("完整版:", proxy_full)

坑一:键名决定「哪种协议的请求走代理」。课堂只写 https 键,抓 http 站点时请求会绕过代理直连, 你以为在隐身,其实真 IP 全暴露了。 坑二:课堂的值是裸 IP:端口,而天琪官方示例(代理IP·试验代码.py)写的是带协议前缀的 "http://IP:端口",且 http/https 两键都给了。requests 两种都接受,但混用时行为差异很难排查, 团队里应统一成官方写法。socks5 代理还要额外 pip install -U requests[socks](官方注释里写着)。

第二步:代理从哪来——接口提取与两批存档清单#

课堂示例2 调天琪 API 一次取 5 个 IP 并存盘:

python
url = 'http://api.tianqiip.com/getip?secret=gvri53xi35dw74rp&num=5&type=txt&lb=%5Cn&port=2&time=3&mr=1&sign=...'response = requests.get(url, headers=headers)with open('ip_addr.txt', 'w', encoding='utf-8') as file:    file.write(response.text)

第三步:timeout 与 retrying——代理是消耗品#

免费/廉价代理的存活期以分钟计(接口参数 time=3 就是 3 分钟有效期)。所以课堂给每个请求加了两道保险:

python
# timeout=3:3 秒没响应就抛异常断开。不加的话,一个死代理能让程序挂住几分钟,# 整个抓取循环被一个坏 IP 拖死——这是新手代理代码最常见的"假死"。response = requests.get(url, headers=headers, proxies=proxy, timeout=3)
python
from retrying import retry          # 第三方库,本环境未安装,此段不运行 @retry(stop_max_attempt_number=5)   # 装饰器:失败自动重来,最多 5 次def send_request(proxy):    response = requests.get(url, headers=headers, proxies=proxy, timeout=3)    print(response.text)

@retry 本质就是 装饰器:不改一行原代码,给函数加上计时和日志11 讲过的模式: 接收函数、返回新函数,新函数在 try/except 里循环调用原函数。不用库也能写出同构逻辑:

python
attempts = 0def flaky():    global attempts    attempts += 1    if attempts < 3:        raise ConnectionError(f"第{attempts}次:代理没响应(模拟 timeout)")    return "当前IP: 123.181.235.47  来自于: 中国 河北 秦皇岛  电信" def send_with_retry(func, stop_max_attempt_number=5):    for i in range(1, stop_max_attempt_number + 1):        try:            return func()        except Exception as e:            print(f"  第{i}次尝试失败 -> {e}")    raise RuntimeError("重试次数用完") print(send_with_retry(flaky))print("总尝试次数:", attempts)

第四步:读清单的正确姿势与一个 set 陷阱#

python
ip_string = "123.181.235.47:40010\n121.225.86.190:40013\n182.34.16.66:40035\n"# 文件末尾有一个换行符,split 后会多出一个空字符串,[:-1] 把它切掉ip_list = ip_string.split("\n")[:-1]print("IP 数量:", len(ip_list))for ip in ip_list:    host, port = ip.split(":")    print(f"  host={host:<16} port={port}")
python
ip_set = {"49.85.115.23:40045", "27.150.88.162:40002", "119.99.104.32:40017"}print("类型:", type(ip_set).__name__, "| 元素数:", len(ip_set))print("是 list 吗:", isinstance(ip_set, list))

踩坑与例外#

练习#

第 05 讲作业:「使用代理IP访问测试网站,且需要使用timeout和retrying来设置响应时间和重复请求,要求体现出retrying库的作用。」 我的提交版即 代理IP·课后作业.py:get_ip() 提取存盘 → read_ip_address() 读清单 → 追加 3 个失效 IP → @retry(stop_max_attempt_number=3) 的 send_request 逐个测试。 复盘:except requests.exceptions.RequestException 只捕 requests 系异常, 若 retrying 在重试耗尽后抛的是 RetryError,外层还要再捕一层,否则程序照样崩。

连出去#

附:本单元源码与成果清单#

类型笔记
状态已完成
掌握度
标签#代理IP#proxies#timeout#retrying#反爬#请求频率
创建2026-11-15
更新2026-11-15
源码代码/06·网络请求入门/代理 IP 使用
可运行是