scrapy是python中成熟高效的爬虫框架,适合中大型项目,本文以抓取政务网站公告为例,完整演示了项目创建、爬虫编写、数据解析及csv/mysql存储全流程。

Scrapy 是 Python 中最成熟、高效的爬虫框架之一,适合中大型数据抓取项目。它自带异步请求、中间件、管道、选择器等完整组件,无需额外造轮子。下面以抓取一个静态新闻列表页(如某地方政务网站的公示公告)为例,带你完成从创建项目、编写爬虫、解析数据到存入 CSV 和 MySQL 的全流程。
一、环境准备与项目初始化
确保已安装 Python 3.8+ 和 pip。推荐使用虚拟环境隔离依赖:
- 运行 pip install scrapy 安装核心框架
- 执行 scrapy startproject news_spider 创建项目
- 进入项目目录:cd news_spider
生成的目录结构中,spiders/ 存放爬虫脚本,items.py 定义数据字段,pipelines.py 负责数据清洗与存储。
二、定义数据结构与编写爬虫逻辑
在 items.py 中声明要提取的字段:
立即学习“Python免费学习笔记(深入)”;
import scrapy <p>class GovNoticeItem(scrapy.Item): title = scrapy.Field() publish_date = scrapy.Field() url = scrapy.Field() source = scrapy.Field()
在 spiders/ 下新建 notice_spider.py,继承 scrapy.Spider:
import scrapy
from news_spider.items import GovNoticeItem
<p>class NoticeSpider(scrapy.Spider):
name = 'gov_notice'
allowed_domains = ['xx.gov.cn']
start_urls = ['<a href="https://www.php.cn/link/7221cf069a295e443767735660697a24">https://www.php.cn/link/7221cf069a295e443767735660697a24</a>']</p><pre class='brush:python;toolbar:false;'>def parse(self, response):
# 提取每条公告的链接
for href in response.css('ul.notice-list a::attr(href)').getall():
yield response.follow(href, callback=self.parse_detail)
# 翻页(示例:下一页链接含“page=2”)
next_page = response.css('a.next::attr(href)').get()
if next_page:
yield response.follow(next_page, callback=self.parse)
def parse_detail(self, response):
item = GovNoticeItem()
item['title'] = response.css('h1.title::text').get('').strip()
item['publish_date'] = response.css('.date::text').re_first(r'\d{4}-\d{2}-\d{2}')
item['url'] = response.url
item['source'] = 'XX市人民政府'
yield item
注意:CSS 选择器需根据目标网页实际 HTML 结构调整,可先用浏览器开发者工具验证;response.follow() 自动处理相对 URL,比 scrapy.Request 更简洁。
三、配置数据存储方式
Scrapy 默认支持 JSON、CSV、XML 导出,只需命令行指定:
- 保存为 CSV:scrapy crawl gov_notice -o notices.csv
- 追加模式(不覆盖):scrapy crawl gov_notice -o notices.csv --nolog
若需存入 MySQL,需启用 Pipeline。在 pipelines.py 中添加:
import pymysql
<p>class MysqlPipeline:
def open_spider(self, spider):
self.conn = pymysql.connect(
host='localhost', user='root', password='123456',
database='spider_db', charset='utf8mb4'
)
self.cursor = self.conn.cursor()</p><pre class='brush:python;toolbar:false;'>def close_spider(self, spider):
self.cursor.close()
self.conn.close()
def process_item(self, item, spider):
sql = "INSERT INTO notices (title, publish_date, url, source) VALUES (%s, %s, %s, %s)"
self.cursor.execute(sql, (item['title'], item['publish_date'], item['url'], item['source']))
self.conn.commit()
return item
然后在 settings.py 中启用该 Pipeline:
ITEM_PIPELINES = {
'news_spider.pipelines.MysqlPipeline': 300,
}
别忘了提前在 MySQL 中建好表:CREATE TABLE notices (id INT AUTO_INCREMENT PRIMARY KEY, title VARCHAR(255), publish_date DATE, url TEXT, source VARCHAR(100));
四、常见问题与优化建议
实战中容易踩坑的地方:
- 反爬响应(403/503):在 settings.py 添加 ROBOTSTXT_OBEY = False,并设置 DOWNLOAD_DELAY = 1 控制请求频率
- 中文乱码:确保 MySQL 连接参数含 charset='utf8mb4',且数据库、表、字段均为 utf8mb4 编码
- 字段为空:使用 .get('', default='') 或 .re_first() 避免 None 报错
- 调试技巧:在 parse 中插入 print(response.text[:500]) 查看原始 HTML,或用 scrapy shell 'http://xx.gov.cn/xxx' 交互式测试 CSS/XPath
Scrapy 不是黑盒,理解 request → response → item → pipeline 的数据流,就能灵活应对各类抓取场景。小项目用 CSV 快速验证,正式部署建议接入 MySQL 或 Elasticsearch 做后续分析。










