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

相关推荐
陈皮波比茶18 分钟前
Python项目实战-网络机器人(爬虫)
开发语言·网络·爬虫·python·机器人
tang777892 小时前
Scrapy框架动态IP自动轮换集成配置教程
爬虫·tcp/ip·scrapy·架构·爬虫代理·动态ip
傻啦嘿哟16 小时前
英雄联盟皮肤爬虫:爬取全皮肤价格与特效,做比价工具
java·c++·爬虫
Spider赵毅18 小时前
Python爬虫踩坑实录:BeautifulSoup使用中的高频问题排查
爬虫·python·beautifulsoup
TlSfoward1 天前
TLS指纹库的数据质量与误判治理 TLSFOWARD TLS指纹库
爬虫·网络协议·http
天启HTTP1 天前
住宅IP和机房IP有什么区别?爬虫场景实测对比
爬虫·网络协议·tcp/ip
阿图灵1 天前
猫眼票房监控系统实战:z3 约束求解破解字体混淆反爬
爬虫·playwright·反爬·z3·猫眼票房
Patrick在香港1 天前
Python asyncio + aiohttp 并发抓取实战:把同步爬虫改造成 3 倍吞吐量的并发管道
redis·爬虫·python
用户094248568031 天前
第32章:MongoDB 源码编译与调试环境搭建
mongodb·nosql
亿牛云爬虫专家2 天前
爬虫调度系统设计:用 Celery 实现按媒体权重动态调整的抓取频率控制
爬虫·python·隧道代理·舆情采集·媒体权重·频率控制·ip自动轮换