当前位置: 首页 > news >正文

Scrapy爬虫集成MongoDB存储

1:在settings.py文件中添加MongoDB相关配置:

# settings.py# MongoDB配置
MONGO_URI = 'mongodb://localhost:27017'  # MongoDB连接字符串
MONGO_DATABASE = 'yiche_cars'  # 数据库名称
MONGO_COLLECTION = 'car_info'  # 集合名称

2:创建MongoDB管道:

# pipelines.pyimport pymongo
from itemadapter import ItemAdapter
from scrapy.exceptions import DropItemclass MongoDBPipeline:def __init__(self, mongo_uri, mongo_db, collection_name=None):self.mongo_uri = mongo_uriself.mongo_db = mongo_dbself.collection_name = collection_name  # 可选:自定义集合名self.client = Noneself.db = None@classmethoddef from_crawler(cls, crawler):return cls(mongo_uri=crawler.settings.get('MONGO_URI'),mongo_db=crawler.settings.get('MONGO_DATABASE', 'scrapy_db'),collection_name=crawler.settings.get('MONGO_COLLECTION')  # 可选)def open_spider(self, spider):try:self.client = pymongo.MongoClient(self.mongo_uri, serverSelectionTimeoutMS=5000)self.db = self.client[self.mongo_db]# 测试连接self.client.server_info()spider.logger.info("成功连接MongoDB!")except pymongo.errors.ServerSelectionTimeoutError as err:spider.logger.error('MongoDB连接失败: %s', err)raise DropItem("无法连接MongoDB")def close_spider(self, spider):if self.client:self.client.close()def process_item(self, item, spider):# 如果设置了 collection_name,优先使用它,否则使用 spider.namecollection_name = self.collection_name if self.collection_name else spider.nametry:self.db[collection_name].insert_one(ItemAdapter(item).asdict())spider.logger.debug(f"Item 写入 MongoDB: {self.mongo_db}/{collection_name}")except pymongo.errors.PyMongoError as e:spider.logger.error("写入MongoDB错误: %s", e)raise DropItem("写入数据库失败")return item  # 必须返回 item,否则后续 pipeline 无法处理

3:在settings.py中启用MongoDB管道:

# settings.pyITEM_PIPELINES = {'spt_spider.pipelines.MongoPipeline': 300,# 其他管道...
}

运行爬虫:

scrapy crawl yiche

http://www.dtcms.com/a/313896.html

相关文章:

  • 基于单片机空气质量检测/气体检测系统
  • FPGA学习笔记——简单的乒乓缓存(RAM)
  • docker容器命令
  • Dbeaver数据库的安装和使用(保姆级别)
  • 嵌入式硬件篇---OpenMV存储
  • 精品PPT | 企业数字化运营平台总体规划建设方案
  • LeetCode热题100——42. 接雨水
  • AI绘画-Stable Diffusion-WebUI的ControlNet用法
  • 设计模式(一)——抽象工厂模式
  • 蓝河操作系统(BlueOS)内核 (VIVO开源)
  • [spring-cloud: 负载均衡]-源码分析
  • Nginx服务做负载均衡网关
  • Rust ⽣成 .wasm 的极致瘦⾝之道
  • 旧物回收小程序:开启绿色生活新篇章
  • SpringBoot3.x入门到精通系列:3.2 整合 RabbitMQ 详解
  • Ethereum:智能合约开发者的“瑞士军刀”OpenZeppelin
  • 白杨SEO:百度搜索开放平台发布AI计划是什么?MCP网站红利来了?顺带说说其它
  • 剧本杀小程序系统开发:开启沉浸式推理社交新纪元
  • 力扣 hot100 Day65
  • 《Python 实用项目与工具制作指南》 · 前言
  • [自动化Adapt] GUI交互(窗口/元素) | 系统配置 | 非侵入式定制化
  • [特殊字符]️ 整个键盘控制无人机系统框架
  • Qt按键响应
  • 更智能的 RibbonBar Spread.NET 18.2Crack
  • QT:交叉编译mysql驱动库
  • 基于鼠标位置的相机缩放和平移命令的实现(原理+源码)
  • Prompt Engineering
  • 赛博威携手Dify,助力AI在企业的场景化落地
  • 【数据库】使用Sql Server创建索引优化查询速度,一般2万多数据后,通过非索引时间字段排序查询出现超时情况
  • Linux(centos)安全狗