🕷️ Python爬虫实战手册
1. 爬虫基础概念
- 爬虫:用程序自动化获取网页数据的过程。
- 核心步骤:
- 发送请求(Requests)
- 获取响应(HTML/JSON)
- 解析数据(BeautifulSoup / lxml / 正则)
- 存储数据(CSV / 数据库 / Excel)
2. 环境准备
pip install requests beautifulsoup4 lxml pandas
3. 发送请求
import requestsurl = "https://example.com"
headers = {"User-Agent": "Mozilla/5.0"}
resp = requests.get(url, headers=headers, timeout=10)print(resp.status_code)
print(resp.text[:500])
4. 解析网页数据
4.1 使用 BeautifulSoup
from bs4 import BeautifulSoupsoup = BeautifulSoup(resp.text, "lxml")
titles = [t.get_text() for t in soup.select("h2.title")]
print(titles)
4.2 使用正则表达式
import re
pattern = re.compile(r'<h2.*?>(.*?)</h2>')
titles = pattern.findall(resp.text)
print(titles)
5. 数据存储
5.1 保存为 CSV
import pandas as pddf = pd.DataFrame({"title": titles})
df.to_csv("result.csv", index=False, encoding="utf-8-sig")
5.2 保存到数据库
import sqlite3conn = sqlite3.connect("data.db")
df.to_sql("articles", conn, if_exists="replace", index=False)
6. 实战案例:爬取豆瓣电影 Top 250
import requests
from bs4 import BeautifulSoup
import pandas as pdmovies = []
for start in range(0, 250, 25):url = f"https://movie.douban.com/top250?start={start}"headers = {"User-Agent": "Mozilla/5.0"}resp = requests.get(url, headers=headers)soup = BeautifulSoup(resp.text, "lxml")for item in soup.select(".item"):title = item.select_one(".title").get_text()rating = item.select_one(".rating_num").get_text()movies.append({"title": title, "rating": rating})df = pd.DataFrame(movies)
df.to_csv("douban_top250.csv", index=False, encoding="utf-8-sig")
7. 进阶技巧
- 反爬虫应对:
- 设置
headers
模拟浏览器 - 使用
time.sleep()
控制访问频率 - 使用代理 IP 池
- 模拟登录(
requests.Session
/ Selenium)
- 动态网页:
- Selenium / Playwright 控制浏览器
- 抓取接口返回的 JSON 数据
- 并发爬取:
concurrent.futures
线程池asyncio + aiohttp
异步请求
8. 爬虫开发规范
- 遵守网站 robots.txt 协议
- 不要对目标网站造成过大压力
- 数据仅用于学习和研究,避免商业滥用
9. 常见问题排查
问题 | 可能原因 | 解决方案 |
---|
返回403 | UA被封 | 修改 headers 或加代理 |
数据缺失 | 动态加载 | 用 Selenium 或抓接口 |
中文乱码 | 编码问题 | resp.encoding = resp.apparent_encoding |
速度太慢 | 单线程 | 使用并发/异步 |
10. 学习路径建议
- 熟悉
requests
+ BeautifulSoup
基础 - 学会用
pandas
导出数据 - 掌握 反爬虫应对 和 动态网页处理
- 进阶到 异步爬虫 和 分布式爬虫(Scrapy)