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

相关推荐
Delroy2 小时前
Vercel 凌晨突发:agent-browser 来了,减少 93% 上下文!AI 终于有了“操纵现实”的手! 🚀
人工智能·爬虫·机器学习
程序员agions5 小时前
Node.js 爬虫实战指南(三):分布式爬虫架构,让你的爬虫飞起来
分布式·爬虫·node.js
上海云盾-高防顾问7 小时前
防CC攻击不止限速:智能指纹识别如何精准抵御恶意爬虫
爬虫·安全·web安全
特行独立的猫7 小时前
python+Proxifier+mitmproxy实现监听本地网路所有的http请求
开发语言·爬虫·python·http
深蓝电商API7 小时前
Scrapy Spider 参数化:动态传入 start_urls 和自定义设置
爬虫·python·scrapy
CCPC不拿奖不改名7 小时前
基于FastAPI的API开发(爬虫的工作原理):从设计到部署详解+面试习题
爬虫·python·网络协议·tcp/ip·http·postman·fastapi
小白学大数据7 小时前
某程旅行小程序爬虫技术解析与实战案例
爬虫·小程序
程序员agions7 小时前
Node.js 爬虫实战指南(四):反反爬策略大全,和网站斗智斗勇
爬虫·node.js
程序员agions8 小时前
Node.js 爬虫实战指南(二):动态页面爬取,Puppeteer 大显身手
爬虫·node.js
嫂子的姐夫8 小时前
017-续集-贝壳登录(剩余三个参数)
爬虫·python·逆向