1. Python爬虫入门:Requests与BeautifulSoup核心用法解析
最近在技术社区看到不少关于Python爬虫的讨论,特别是Requests库出现"429 Too Many Requests"错误的问题。作为从2015年就开始用Python做数据采集的老手,我想分享一套经过实战检验的爬虫方案。本文不会教你写攻击性代码(如CC攻击),而是专注于合法的网页数据采集技术。
使用Requests+BeautifulSoup这套组合,你可以快速抓取电商价格、新闻资讯或公开API数据。我曾用这个方案帮朋友抓取过家电比价数据,单日稳定采集10万条记录无压力。下面就从最基础的安装配置开始,带你避开新手常见的坑。
需要模型API调用? 免费领10W Token,多模型网关一键接入 Claude、DeepSeek 等主流模型。
2. 环境准备与工具选型
2.1 Python环境配置要点
推荐使用Python 3.8+版本,这个区间对第三方库兼容性最好。新手常犯的错误是:
- 同时安装多个Python版本导致路径冲突
- 忘记勾选"Add Python to PATH"安装选项
- 使用系统自带的Python(如macOS的2.7版本)
验证安装成功的正确姿势:
bash复制python --version pip list
2.2 必备库安装指南
通过pip安装时建议使用清华源加速:
bash复制pip install requests beautifulsoup4 -i https://pypi.tuna.tsinghua.edu.cn/simple
常见安装问题排查:
- 报错"Could not find a version":检查Python版本是否过旧
- 报错"Permission denied":在命令前加上
--user参数 - 报错"SSLError":临时使用
--trusted-host pypi.tuna.tsinghua.edu.cn
3. Requests库实战技巧
3.1 基础请求与反爬应对
最简单的GET请求示例:
python复制import requests
response = requests.get('https://example.com')
print(response.status_code) # 200
print(response.text[:500]) # 截取前500字符
应对429错误的五大策略:
- 添加随机延迟:
time.sleep(random.uniform(1,3)) - 轮换User-Agent:准备10个以上常见浏览器UA
- 使用代理IP池:推荐付费服务而非免费代理
- 设置请求间隔:
requests.get(..., timeout=(3.1, 7)) - 遵守robots.txt规则:道德爬虫的基本素养
3.2 高级请求参数详解
带参数的POST请求示例:
python复制payload = {'key1': 'value1', 'key2': ['value2', 'value3']}
headers = {'User-Agent': 'Mozilla/5.0'}
response = requests.post('https://httpbin.org/post',
data=payload,
headers=headers)
关键参数说明:
proxies:配置代理字典cookies:维持会话状态verify=False:跳过SSL验证(慎用)allow_redirects=False:禁止重定向
4. BeautifulSoup解析实战
4.1 HTML解析器选择对比
| 解析器 | 速度 | 容错性 | 依赖库 |
|---|---|---|---|
| html.parser | 中 | 中 | 内置 |
| lxml | 快 | 好 | 需安装 |
| html5lib | 慢 | 极好 | 需安装 |
推荐初始化方式:
python复制from bs4 import BeautifulSoup
soup = BeautifulSoup(html_doc, 'lxml') # 需先pip install lxml
4.2 常用选择方法示例
python复制# 通过标签名查找
soup.find_all('a')
# 通过CSS类查找
soup.select('.article-title')
# 属性选择
soup.find(attrs={"data-id": "123"})
# 文本匹配
soup.find_all(text=re.compile("Python"))
5. 完整爬虫项目示例
5.1 新闻网站爬取实战
以抓取某新闻网站标题为例:
python复制import requests
from bs4 import BeautifulSoup
import time
headers = {
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36'
}
def get_news(page=1):
url = f'https://news.example.com/page/{page}'
try:
response = requests.get(url, headers=headers)
soup = BeautifulSoup(response.text, 'lxml')
articles = soup.select('.news-item')
for item in articles:
title = item.find('h2').get_text(strip=True)
print(title)
time.sleep(2) # 礼貌性延迟
except Exception as e:
print(f"抓取失败: {e}")
get_news(1)
5.2 数据存储方案
三种常用存储方式对比:
- CSV文件:适合中小规模数据
python复制import csv with open('data.csv', 'a', newline='') as f: writer = csv.writer(f) writer.writerow([title, url]) - MySQL数据库:适合结构化数据
- MongoDB:适合非结构化数据
6. 反爬虫进阶应对策略
6.1 验证码处理方案
- 简单验证码:使用Tesseract OCR识别
- 复杂验证码:接入打码平台(如超级鹰)
- 滑动验证码:selenium模拟人工操作
6.2 浏览器指纹防护
现代网站常检测以下特征:
- WebGL渲染器
- Canvas指纹
- WebRTC泄漏
- 字体列表
解决方案:
python复制from fake_useragent import UserAgent
ua = UserAgent()
headers = {'User-Agent': ua.random}
7. 性能优化技巧
7.1 多线程加速方案
使用concurrent.futures实现:
python复制from concurrent.futures import ThreadPoolExecutor
urls = [f'https://example.com/page/{i}' for i in range(1,6)]
def fetch(url):
return requests.get(url).text
with ThreadPoolExecutor(max_workers=3) as executor:
results = executor.map(fetch, urls)
7.2 断点续爬实现
记录已爬取URL的简单方案:
python复制import pickle
# 保存进度
with open('progress.pkl', 'wb') as f:
pickle.dump(crawled_urls, f)
# 读取进度
try:
with open('progress.pkl', 'rb') as f:
crawled_urls = pickle.load(f)
except FileNotFoundError:
crawled_urls = set()
8. 法律与道德规范
重要注意事项:
- 严格遵守网站的robots.txt规定
- 控制请求频率(建议≥3秒/次)
- 不抓取个人隐私数据
- 商用前获取网站授权
- 在header中声明爬虫身份
典型违规案例:
- 未经授权抓取用户评论
- 绕过付费墙获取内容
- 对API接口发起高频请求
我在实际项目中总结的经验是:凌晨1-5点采集数据触发反爬的概率最低,对于重要项目最好准备至少5个备用IP轮换使用。当遇到"429 Too Many Requests"时,不要立即重试,应该先分析响应头中的Retry-After字段。
