爬虫完整流程详解(7大核心步骤+实战技巧)
一、爬虫完整工作流程
以下是爬虫开发的完整流程,我将结合具体技术点和实战经验展开说明:
1. 目标分析与前期准备
- 网站技术分析:
- 使用浏览器开发者工具(F12)检查:
- Network面板查看数据加载方式(XHR请求/静态HTML)
- Elements面板分析DOM结构
- 识别反爬机制:
- 检查
robots.txt
(如:https://www.zhihu.com/robots.txt) - 测试直接访问是否返回完整数据
- 检查
- 使用浏览器开发者工具(F12)检查:
- 法律风险评估:
- 检查网站服务条款(如微博禁止未经授权的爬取)
- 控制爬取频率(建议≥3秒/请求)
实战案例:爬取知乎热榜需要先模拟登录获取cookies
2. 发送HTTP请求(核心环节)
请求方式选择
场景 | 工具 | 示例代码 |
---|---|---|
简单静态页 | requests | requests.get(url, headers=headers) |
动态渲染页 | selenium | driver.get(url); html = driver.page_source |
大规模爬取 | Scrapy | yield scrapy.Request(url, callback=self.parse) |
关键请求参数
headers = {
"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36",
"Cookie": "session_id=abc123",
"Referer": "https://www.example.com"
}
proxies = {
"http": "http://10.10.1.10:3128",
"https": "http://10.10.1.10:1080"
}
response = requests.get(
url,
headers=headers,
proxies=proxies,
timeout=10
)
高级技巧
- 自动重试机制(应对429/503错误)
from tenacity import retry, stop_after_attempt
@retry(stop=stop_after_attempt(3))
def fetch_url(url):
return requests.get(url)
3. 内容解析(数据提取核心)
解析工具对比
工具 | 速度 | 易用性 | 适用场景 | 示例 |
---|---|---|---|---|
BeautifulSoup | 慢 | ★★★★★ | 简单页面 | soup.select('div.main') |
lxml | 快 | ★★★★ | XPath复杂查询 | tree.xpath('//div[@class="main"]') |
PyQuery | 中 | ★★★★ | jQuery风格 | doc('div.main').text() |
**实战解析示例
# BeautifulSoup + CSS选择器
from bs4 import BeautifulSoup
soup = BeautifulSoup(html, 'lxml')
titles = [h2.text for h2 in soup.select('h2.title')]
# lxml + XPath(适合复杂嵌套)
from lxml import etree
tree = etree.HTML(html)
prices = tree.xpath('//span[@class="price"]/text()')
# 正则表达式(提取特定模式)
import re
phones = re.findall(r'1[3-9]\d{9}', html)
4. 数据清洗与验证
- 文本处理:
- 去除空白字符:
text.strip()
- 统一编码:
text.encode('utf-8').decode('utf-8')
- 去除空白字符:
- 数据验证:
- 手机号校验:
re.match(r'^1[3-9]\d{9}$', phone)
- 邮箱校验:
re.match(r'^[\w.-]+@[\w.-]+\.\w+$', email)
- 手机号校验:
5. 数据存储方案
存储方式对比
存储类型 | 优点 | 缺点 | 适用场景 |
---|---|---|---|
CSV | 无需数据库,Excel可打开 | 无索引,查询慢 | 小型数据集(<10万条) |
MySQL | 支持复杂查询,事务 | 需要维护数据库 | 结构化数据存储 |
MongoDB | 灵活Schema,适合JSON | 占用内存大 | 非结构化数据(如网页快照) |
Redis | 内存存储,速度快 | 数据易丢失 | 临时缓存/去重队列 |
**代码示例
# CSV存储
import csv
with open('data.csv', 'a', newline='') as f:
writer = csv.writer(f)
writer.writerow(['title', 'price'])
# MySQL存储
import pymysql
conn = pymysql.connect(host='localhost', user='root', password='123456', db='spider')
cursor = conn.cursor()
cursor.execute("INSERT INTO products VALUES (%s, %s)", ('iPhone', 5999))
conn.commit()
# MongoDB存储
from pymongo import MongoClient
client = MongoClient('mongodb://localhost:27017/')
db = client['spider_db']
db.products.insert_one({"name": "iPhone", "price": 5999})
6. 反爬对抗策略
常见反爬手段及破解方法
反爬类型 | 破解方案 | 实现代码 |
---|---|---|
User-Agent检测 | 轮换UA | headers['User-Agent'] = random.choice(ua_list) |
IP限制 | 代理IP池 | requests.get(url, proxies={"http": proxy}) |
验证码 | OCR识别/打码平台 | 使用ddddocr 库 |
行为分析 | 模拟鼠标移动 | selenium.ActionChains(driver).move_by_offset(10, 20) |
高级技巧
- 浏览器指纹模拟(使用
undetected-chromedriver
) - WebSocket协议抓取(如股票实时数据)
- 分布式爬虫架构(Scrapy+Redis)
7. 任务调度与监控
- 定时任务:
- 简单方案:
APScheduler
from apscheduler.schedulers.blocking import BlockingScheduler sched = BlockingScheduler() @sched.scheduled_job('interval', hours=1) def job(): run_spider() sched.start()
- 简单方案:
- 异常监控:
- 邮件报警:
smtplib
发送错误日志 - Prometheus+Grafana监控爬虫状态
- 邮件报警:
二、完整爬虫项目架构
├── spiders/ # 爬虫核心
│ ├── base_spider.py # 基础爬虫类
│ ├── zhihu_spider.py # 知乎爬虫实现
│ └── douban_spider.py # 豆瓣爬虫实现
├── utils/
│ ├── proxy.py # 代理IP管理
│ ├── captcha.py # 验证码处理
│ └── logger.py # 日志系统
├── storage/
│ ├── mysql_client.py # 数据库操作
│ └── file_store.py # 文件存储
└── config.py # 全局配置
三、性能优化要点
-
并发控制:
- 多线程:
concurrent.futures.ThreadPoolExecutor
- 异步IO:
aiohttp
+asyncio
import aiohttp async def fetch(session, url): async with session.get(url) as response: return await response.text()
- 多线程:
-
缓存利用:
- 使用
requests-cache
避免重复请求
import requests_cache requests_cache.install_cache('demo_cache')
- 使用
-
增量爬取:
- 记录已爬URL:
Redis集合
去重 - 基于时间戳:只爬取
last_modified
之后的数据
- 记录已爬URL:
四、法律与道德规范
- 遵守
robots.txt
协议 - 控制爬取频率(≥3秒/请求)
- 不爬取敏感数据(用户隐私、商业秘密)
- 商用前获取网站授权
五、学习路线建议
- 初级阶段:
requests
+BeautifulSoup
实战 - 中级阶段:
Scrapy
框架 + 反爬破解 - 高级阶段:
- 分布式爬虫(Scrapy-Redis)
- 智能解析(机器学习识别页面结构)
- 浏览器自动化集群(Selenium Grid)
建议从豆瓣电影Top250这类开放数据开始练习,逐步挑战更复杂的网站如电商、社交媒体平台。