以下是Python网络爬虫的实战开发指南,涵盖核心技术、反爬策略及典型应用场景:
一、Python爬虫核心技术栈
- 核心工具库
python
复制
基础请求库
import requests # HTTP请求
from bs4 import BeautifulSoup # HTML解析
import selenium.webdriver # 动态页面渲染
进阶工具
import scrapy # 爬虫框架
import pandas as pd # 数据清洗
2. 爬虫开发四步流程
目标分析
使用Chrome开发者工具(F12)分析网页结构
检查XHR请求获取API接口(适用于动态加载数据)
数据抓取
python
复制
基础GET请求示例
headers = {‘User-Agent’: ‘Mozilla/5.0’}
response = requests.get(url=‘https://example.com’, headers=headers)
print(response.status_code) # 200表示成功
数据解析
python
复制
BeautifulSoup解析示例
soup = BeautifulSoup(response.text, ‘lxml’)
titles = soup.select(‘div.article > h2’) # CSS选择器
for title in titles:
print(title.get_text())
数据存储
python
复制
存储到CSV文件
import csv
with open(‘data.csv’, ‘w’, newline=‘’, encoding=‘utf-8’) as f:
writer = csv.writer(f)
writer.writerow([‘标题’, ‘链接’])
for item in data:
writer.writerow([item[‘title’], item[‘url’]])
二、反爬机制破解策略
- 常见反爬类型与应对
反爬类型 破解方案
User-Agent检测 轮换随机UA头
IP封禁 使用代理IP池(免费:快代理,付费:芝麻代理)
验证码 OCR识别(Tesseract)或打码平台
动态加载 Selenium/Puppeteer模拟浏览器
请求频率限制 设置随机延迟(time.sleep(1~3) - 动态页面抓取实战
python
复制
from selenium import webdriver
from selenium.webdriver.chrome.options import Options
无头浏览器配置
chrome_options = Options()
chrome_options.add_argument(‘–headless’)
driver = webdriver.Chrome(options=chrome_options)
driver.get(“https://dynamic-website.com”)
driver.implicitly_wait(10) # 等待动态加载
content = driver.page_source
driver.quit()
三、Scrapy框架进阶应用
- 项目创建与结构
bash
复制
scrapy startproject my_spider
cd my_spider
scrapy genspider example example.com
复制
my_spider/
├── scrapy.cfg
└── my_spider/
├── items.py # 数据模型
├── middlewares.py # 中间件
├── pipelines.py # 数据管道
├── settings.py # 配置
└── spiders/ # 爬虫文件 - 核心组件代码示例
python
复制
items.py 定义数据结构
import scrapy
class ProductItem(scrapy.Item):
name = scrapy.Field()
price = scrapy.Field()
pipelines.py 数据存储
class MongoDBPipeline:
def process_item(self, item, spider):
db = spider.client[‘mydb’]
db.products.insert_one(dict(item))
return item
settings.py 关键配置
USER_AGENT = ‘Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36’
DOWNLOAD_DELAY = 2
ITEM_PIPELINES = {‘my_spider.pipelines.MongoDBPipeline’: 300}
四、典型实战案例
案例1:电商价格监控
python
复制
def monitor_price(url):
while True:
res = requests.get(url)
soup = BeautifulSoup(res.text, ‘lxml’)
price = soup.find(‘span’, class_=‘price’).text
if float(price) < 100: # 设置阈值
send_email_alert(price) # 触发邮件通知
time.sleep(3600) # 每小时检查一次
案例2:新闻聚合爬虫(Scrapy版)
python
复制
class NewsSpider(scrapy.Spider):
name = ‘news’
start_urls = [‘http://news.site/page=1’]
def parse(self, response):
for article in response.css('div.news-item'):
yield {
'title': article.css('h2::text').get(),
'date': article.xpath('.//span[@class="time"]/text()').get()
}
# 翻页处理
next_page = response.css('a.next-page::attr(href)').get()
if next_page:
yield response.follow(next_page, self.parse)
五、爬虫法律与伦理
合规要求
遵守网站robots.txt协议(如禁止爬取/admin/路径)
不抓取个人隐私数据(手机号、身份证等)
性能优化建议
使用Scrapy-Redis构建分布式爬虫
启用AutoThrottle扩展自动调整请求频率
通过Pyppeteer替代Selenium提升渲染效率
六、调试与问题排查
常见错误处理
python
复制
try:
response = requests.get(url, timeout=5)
except requests.exceptions.ProxyError:
print(“代理服务器异常,切换IP”)
except requests.exceptions.ConnectionError:
print(“网络连接异常,重试中…”)
调试工具推荐
Postman:测试API接口
Charles:抓包分析网络请求
Scrapy Shell:实时测试选择器
扩展学习资源:
官方文档:Scrapy Documentation
实战项目:GitHub热门爬虫仓库
数据清洗:Pandas数据处理技巧
掌握这些技能后,可尝试构建舆情监控、商品比价、搜索引擎爬虫等实用系统,但切记遵守相关法律法规。