

新闻资讯
技术教程Scrapy是Python中成熟高效的爬虫框架,适合中大型项目,本文以抓取政务网站公告为例,完整演示了项目创建、爬虫编写、数据解析及CSV/MySQL存储全流程。
Scrapy 是 Python 中最成熟、高效的爬虫框架之一,适合中大型数据抓取项目。它自带异步请求、中间件、管道、选择器等完整组件,无需额外造轮子。下面以抓取一个静态新闻列表页(如某地方政务网站的公示公告)为例,带你完成从创建项目、编写爬虫、解析数据到存入 CSV 和 MySQL 的全流程。
确保已安装 Python 3.8+ 和 pip。推荐使用虚拟环境隔离依赖:
生成的目录结构中,spiders/ 存放爬虫脚本,items.py 定义数据字段,pipelines.py 负责数据清洗与存储。
在 items.py 中声明要提取的字段:
import scrapyclass 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 GovNoticeItemclass NoticeSpider(scrapy.Spider): name = 'gov_notice' allowed_domains = ['xx.gov.cn'] start_urls = ['https://www./link/7221cf069a295e443767735660697a24']
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 导出,只需命令行指定:
若需存入 MySQL,需启用 Pipeline。在 pipelines.py 中添加:
import pymysqlclass 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()
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));
四、常见问题与优化建议
实战中容易踩坑的地方:
Scrapy 不是黑盒,理解 request → response → item → pipeline 的数据流,就能灵活应对各类抓取场景。小项目用 CSV 快速验证,正式部署建议接入 MySQL 或 Elasticsearch 做后续分析。