手把手讲清楚 requests 库的核心用法、多页遍历策略、代理配置与异常处理,适合有 Python 基础的初学者。
目录
1.爬虫是什么,能做什么
2.发送第一个 GET 请求
3.多页遍历的两种写法
4.为什么需要 User-Agent
5.使用代理隐藏 IP
6.超时与异常处理
7.处理 HTTPS 与 JSON 响应
8.代理匿名度等级
①爬虫是什么,能做什么
网络爬虫(Web Crawler)本质上是一段自动发送 HTTP 请求、接收响应并保存内容的程序。浏览器打开网页时做的事,爬虫用代码重演一遍。常见场景:批量下载图片、采集价格数据、监控页面变动、构建搜索索引等。
Python 的 requests 库是最常用的 HTTP 客户端,安装方式:pip install requests。更复杂的场景(渲染 JS)需要 Selenium 或 Playwright,本文聚焦静态页面。
②发送第一个 GET 请求
最简单的爬虫只需几行:构造 URL、带上 Headers、发送请求、保存响应内容。
import requestsdef main(): url = "http://example.com/list/page-1/" headers = { "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) " "AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120"} resp = requests.get(url=url, headers=headers)withopen("page.html", "wb") as f: f.write(resp.content) # content 是原始字节,text 是解码后字符串if __name__ == "__main__": main()
③多页遍历的两种写法
网站内容往往分页,URL 规律通常是某个数字递增。利用 Python 字符串格式化可以批量生成 URL。
写法 A:先生成列表,再遍历
url_tpl = "http://example.com/list/page-{}-0/"url_list = [url_tpl.format(i) for i in range(1, 15)] # 生成第1-14页for idx, url in enumerate(url_list): resp = requests.get(url=url, headers=headers) with open(f"page_{idx}.html", "wb") as f: f.write(resp.content)
写法 B:直接在循环中构造 URL
for i in range(1, 15): url = url_tpl.format(i) resp = requests.get(url=url, headers=headers) with open(f"page_{i}.html", "wb") as f: f.write(resp.content)
④为什么必须设置 User-Agent
服务器通过请求头中的 User-Agent 字段判断访问者是浏览器还是爬虫。不设置时,requests 默认发送 python-requests/x.x.x,很容易被识别并拦截(返回 403 或空内容)。
将 UA 设置为常见浏览器字符串,是最基础的反反爬措施。进阶做法是维护一个 UA 列表,每次请求随机选取,进一步降低被识别概率。
⑤使用代理隐藏真实 IP
高频爬取同一网站时,源 IP 可能被封禁。代理服务器作为中间人,让请求看起来来自不同地址。
# HTTP 代理proxies = {"http": "http://代理IP:端口", "https": "http://代理IP:端口"}# SOCKS5 代理(需安装 pip install requests[socks])proxies = {"http": "socks5://代理IP:端口", "https": "socks5://代理IP:端口"}resp = requests.get(url, headers=headers, proxies=proxies, timeout=5)
⑥超时与异常处理
网络请求天然不可靠,必须设置超时并捕获异常,否则程序可能无限等待或崩溃退出。
import requestsdef fetch(url, headers, proxies=None): try: resp = requests.get( url=url, headers=headers, proxies=proxies, timeout=5 # 连接+读取超时,单位秒) if resp.status_code == 200: return resp.content else: print(f"请求失败,状态码:{resp.status_code}") except requests.exceptions.Timeout: print("请求超时,跳过") except requests.exceptions.ProxyError: print("代理不可用") except Exception as e: print(f"未知错误:{e}") return None
⑦处理 HTTPS 与 JSON 响应
requests 对 HTTPS 的处理与 HTTP 完全一致,直接使用 https:// 地址即可。若遇到 SSL 证书错误(自签名证书),可临时关闭验证(不推荐用于生产):
resp = requests.get(url, headers=headers, verify=False) # 关闭 SSL 验证
当接口返回 JSON 格式数据时,无需手动解析:
resp = requests.get(api_url, headers=headers)data = resp.json() # 自动解析为 Python dict/listprint(data["items"])
⑧代理匿名度等级
代理并非铁板一块,服务器获取到的信息量因代理类型而异:
类型 | 服务器是否知道你用了代理 | 服务器获取的 IP | 适用场景 |
透明代理 | 知道 高风险 | 真实 IP | 适合反爬 |
匿名代理 | 知道 中等 | 代理 IP(知道你用了代理) | 一般场景 |
混淆代理 | 知道 中等 | 伪造的假 IP | 干扰追踪 |
高匿代理 | 不知道 推荐 | 代理 IP(无法发现代理 | 高频爬取 |
✓小结
核心库 | 必须携带 | 反封 IP | 稳定性 |
requests | User-Agent | 代理池 | 超时 + 异常 |
一个可用的爬虫,最低限度需要:正确的请求头、合理的超时设置、异常捕获三件套。在此基础上叠加代理、Cookie 管理、频率控制,才能应对各种反爬场景。后续文章将进一步介绍 Cookie 登录、BeautifulSoup/lxml 解析、以及 Scrapy 框架的使用。