🗣 Wd提问: scrapy mysql存储
🤖 Ai回答: 在使用 Scrapy 爬取数据并存储到 MySQL 数据库时,通常有以下几种方式:
1、通过 `pipelines.py` 实现持久化存储
2、使用异步方式(推荐)避免阻塞爬虫
3、连接数据库的方式:同步(MySQLdb/PyMySQL)或异步(Twisted adbapi)
下面是一个完整的示例,展示如何将 Scrapy 抓取的数据存入 MySQL。
✅ 一、准备工作
1、安装依赖
bash
pip install scrapy pymysql twisted[mysql]
推荐使用 `PyMySQL`,它是纯 Python 的 MySQL 驱动,兼容性好。
2、创建 MySQL 数据库和表
sql
CREATE DATABASE scrapy_db CHARACTER SET utf8mb4;
USE scrapy_db;
CREATE TABLE news (
id INT AUTO_INCREMENT PRIMARY KEY,
title VARCHAR(255) NOT NULL,
url VARCHAR(500),
publish_date DATE,
content TEXT
);
✅ 二、Scrapy 项目配置
假设你的项目名为 `myproject`,结构如下:
myproject/
├── myproject/
│ ├── spiders/
│ │ └── example_spider.py
│ ├── items.py
│ ├── pipelines.py
│ └── settings.py
└── scrapy.cfg
✅ 三、定义 Item(items.py)
python
import scrapy
class NewsItem(scrapy.Item):
title = scrapy.Field()
url = scrapy.Field()
publish_date = scrapy.Field()
content = scrapy.Field()
✅ 四、编写 Pipeline(pipelines.py)
使用 Twisted 的 `adbapi` 实现异步插入,避免阻塞爬虫。
python
from twisted.enterprise import adbapi
import pymysql
class MySQLPipeline:
def __init__(self, dbpool):
self.dbpool = dbpool
@classmethod
def from_crawler(cls, crawler):
从 settings 中读取数据库配置
db_settings = {
'host': crawler.settings.get('MYSQL_HOST', 'localhost'),
'db': crawler.settings.get('MYSQL_DBNAME', 'scrapy_db'),
'user': crawler.settings.get('MYSQL_USER', 'root'),
'passwd': crawler.settings.get('MYSQL_PASSWD', 'password'),
'charset': 'utf8mb4',
'cursorclass': pymysql.cursors.DictCursor,
'autocommit': True,
}
使用 adbapi 创建连接池
dbpool = adbapi.ConnectionPool(pymysql, db_settings)
return cls(dbpool)
def process_item(self, item, spider):
使用异步方式插入数据
d = self.dbpool.runInteraction(self._do_insert, item)
d.addErrback(self._handle_error, item, spider)
return item
def _do_insert(self, cursor, item):
sql =
INSERT INTO news (title, url, publish_date, content)
VALUES (%s, %s, %s, %s)
ON DUPLICATE KEY UPDATE title=VALUES(title)
cursor.execute(sql, (
item.get('title'),
item.get('url'),
item.get('publish_date'),
item.get('content')
))
def _handle_error(self, failure, item, spider):
处理异常(如重复主键、字段超长等)
spider.logger.error(f数据库错误: {failure} | Item: {item})
✅ 五、配置 settings.py
python
启用 Pipeline
ITEM_PIPELINES = {
'myproject.pipelines.MySQLPipeline': 300,
}
MySQL 配置
MYSQL_HOST = 'localhost'
MYSQL_DBNAME = 'scrapy_db'
MYSQL_USER = 'root'
MYSQL_PASSWD = 'your_password'
可选:设置日志等级
LOG_LEVEL = 'INFO'
✅ 六、编写爬虫(example_spider.py)
python
import scrapy
from myproject.items import NewsItem
class ExampleSpider(scrapy.Spider):
name = 'example'
start_urls = ['https://httpbin.org/html'] 示例 URL,替换为你的真实目标
def parse(self, response):
item = NewsItem()
item['title'] = response.css('h1::text').get() or No Title
item['url'] = response.url
item['publish_date'] = '2024-01-01' 示例日期
item['content'] = response.xpath('//body//text()').getall()
yield item
✅ 七、运行爬虫
bash
scrapy crawl example
如果一切正常,数据会自动插入 MySQL 的 `news` 表中。
✅ 注意事项
1、编码问题:确保数据库、表、字段都使用 `utf8mb4` 编码,支持中文和 emoji。
2、异常处理:`_handle_error` 可以捕获 SQL 错误,便于调试。
3、去重:可在 SQL 中使用 `ON DUPLICATE KEY UPDATE` 或在爬虫中使用 `DUPEFILTER_CLASS`。
4、性能优化**:大量数据可考虑批量插入(需修改 pipeline 使用 `executemany`)。
✅ 批量插入优化(可选)
若要提升性能,可以累积多个 item 再批量插入:
python
def __init__(self, dbpool):
self.dbpool = dbpool
self.items_buffer = []
def open_spider(self, spider):
self.items_buffer = []
def close_spider(self, spider):
if self.items_buffer:
self._insert_batch(self.items_buffer)
self.items_buffer.clear()
def process_item(self, item, spider):
self.items_buffer.append(item)
if len(self.items_buffer) = 100: 每100条执行一次批量插入
self._insert_batch(self.items_buffer)
self.items_buffer.clear()
return item
def _insert_batch(self, items):
def _do_insert(conn):
cursor = conn.cursor()
sql = INSERT INTO news (title, url, publish_date, content) VALUES (%s, %s, %s, %s)
data = [
(item['title'], item['url'], item['publish_date'], item['content'])
for item in items
]
cursor.executemany(sql, data)
d = self.dbpool.runInteraction(_do_insert)
d.addErrback(self._handle_error_batch, items)
如有更多需求(如更新、去重、字段映射),欢迎继续提问!
📣 商家广告:





0
IP地址: 89.124.99.124
搜索次数: 0
提问时间: 2025-11-12 03:10:15
🛒 域名购买:
kfdy.cn
815.red
kou.red
61.gold
0.bj.cn
dxgm.cn
hv.gs
9.bj.cn
al3.net
jiu.red
❓️ 热门提问:
访问ftp服务器
ip 本地
站群程序搭建服务公司软件
ftp服务器软件免费
广告设计师资格证怎么考
域名的注册过程
租用服务器出租
ip第一个
ip人物建模
自定义dns服务器
豌豆Ai站群搜索引擎系统
🌐 域名评估:
5a.jx.cn
59.gold
evtol.ha.cn
aaaa.cafe
tt.yn.cn
logo.xin
musk.biz
nk.com.hk
qptj.cn
mg.gs
⛏ 最新挖掘:
凯里酸汤鱼
贵阳烤脑花
都匀毛尖茶
花溪牛肉粉
贵阳烤生蚝
贵阳烤豆腐
贵阳纸包鱼
贵阳特色菜
🖌 热门作画:
🤝 关于我们:
豌豆Ai
域名
建站
站群
留痕
推广
评估
源码
开发Ai
工具
日记
价格
加盟
广告
流量
留言
联系
🗨 加入群聊:
🔗 友情链接:
平塘县综合福利院
北京网络推广
ai提问
🧰 站长工具:
Ai工具 whois查询 搜索
📢 温馨提示:本站所有问答由Ai自动创作,内容仅供参考,若有误差请用“联系”里面信息通知我们人工修改或删除。
👉 技术支持:本站由豌豆Ai提供技术支持,使用的最新版:《豌豆Ai站群搜索引擎系统 V.25.10.25》搭建本站。