Scrapy爬虫集成MongoDB存储

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

python 复制代码
# settings.py

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

2:创建MongoDB管道:

python 复制代码
# pipelines.py

import pymongo
from itemadapter import ItemAdapter
from scrapy.exceptions import DropItem

class MongoDBPipeline:
    def __init__(self, mongo_uri, mongo_db, collection_name=None):
        self.mongo_uri = mongo_uri
        self.mongo_db = mongo_db
        self.collection_name = collection_name  # 可选:自定义集合名
        self.client = None
        self.db = None

    @classmethod
    def 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.name
        collection_name = self.collection_name if self.collection_name else spider.name
        
        try:
            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管道:

python 复制代码
# settings.py

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

运行爬虫:

scrapy crawl yiche

相关推荐
傻啦嘿哟6 小时前
某招聘平台爬虫:爬取招聘岗位数据,分析各城市薪资水平
开发语言·爬虫·python
隐擎fox7 小时前
深入理解网络传输层安全:TLS 指纹识别(JA3/JA4)原理与 Python 协议层检测实战
爬虫·python·网络协议·安全·网络安全·https
Horn Still Sounds9 小时前
51单片机入门:硬件基础、位运算、数码管动态显示完整梳理
嵌入式硬件·mongodb·51单片机
wuyk55510 小时前
Python网络爬虫入门到实战 第01章:爬虫到底是什么?原理、流程、合法性、风险全解析(零基础必看)
开发语言·爬虫·python
SEO_juper14 小时前
你的服务器正在被 AI 爬虫“白嫖“带宽:2026 用日志把 Googlebot 和 AI 洪流分开算账(附脚本)
运维·人工智能·爬虫·python·chatgpt·seo
djarmy1 天前
MAIN.c(1): warning C318: can’t open file ‘STC8G.H’ 报错 解决 分析
c语言·开发语言·mongodb
may_一一2 天前
MongoDB数据查看(Studio 3T)
数据库·mongodb
m0_547486662 天前
《Python爬虫大数据采集与挖掘》全套PPT课件2026
爬虫·python·powerpoint
Experience-摆渡2 天前
MediaCrawler舆情分析系统实测:7大平台爬虫的商用授权红线与风控现状
爬虫
圆脸脸lxj2 天前
scrapy框架开发中pipelines模块将数据写入记事本中
scrapy