插入mongodb数据库错误self.collection.insert报错

TypeError: ‘Collection’ object is not callable. If you meant to call the ‘insert’ method on a ‘Collection’ object it is failing because no such method exists.

  1. 先检查自己的数据中是否有空的。或者空行,有的话进行修改,直到没有空数据再将self.collection.insert改为self.collection.insert_one。

2.这个通常是版本问题,如果你的版本使用insert会报错,那改成insert_one就可以了

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
好的,以下是详细的Python代码实现: 首先,需要创建一个Scrapy项目: ``` scrapy startproject xia_chu_fang ``` 然后,在项目中创建一个Spider: ``` cd xia_chu_fang scrapy genspider xia_chu_fang_spider xiachufang.com ``` 接着,打开xia_chu_fang_spider.py文件,将以下代码替换进去: ```python import scrapy from pymongo import MongoClient class XiaChuFangSpider(scrapy.Spider): name = 'xia_chu_fang' # 定义起始URL start_urls = ['https://www.xiachufang.com/explore/menu/collect/'] def parse(self, response): # 解析出菜品的标题和作者 for dish in response.css('div.pure-u-3-4'): title = dish.css('p.name > a::text').get() author = dish.css('p.author > a::text').get() # 将数据存入MongoDB数据库中 client = MongoClient('localhost', 27017) db = client['xia_chu_fang'] collection = db['dishes'] collection.insert_one({'title': title, 'author': author}) # 获取下一页的URL next_page = response.css('div.pager > a.next::attr(href)').get() if next_page is not None: yield response.follow(next_page, self.parse) ``` 这个Spider会从指定的URL开始爬取,然后解析出每个菜品的标题和作者,并将数据存入MongoDB数据库中。同时,它会自动翻页,直到所有的菜品都被爬取完毕。 最后,需要在settings.py文件中添加MongoDB的配置: ```python ITEM_PIPELINES = {'xia_chu_fang.pipelines.XiaChuFangPipeline': 300} MONGODB_SERVER = "localhost" MONGODB_PORT = 27017 MONGODB_DB = "xia_chu_fang" MONGODB_COLLECTION = "dishes" ``` 然后,创建一个pipelines.py文件,将以下代码替换进去: ```python import pymongo class XiaChuFangPipeline(object): def __init__(self, server, port, db, collection): self.server = server self.port = port self.db = db self.collection = collection @classmethod def from_crawler(cls, crawler): return cls( server = crawler.settings.get('MONGODB_SERVER'), port = crawler.settings.get('MONGODB_PORT'), db = crawler.settings.get('MONGODB_DB'), collection = crawler.settings.get('MONGODB_COLLECTION') ) def open_spider(self, spider): self.client = pymongo.MongoClient(self.server, self.port) self.db = self.client[self.db] def close_spider(self, spider): self.client.close() def process_item(self, item, spider): self.db[self.collection].insert_one(dict(item)) return item ``` 这个pipeline会将Spider爬取到的数据存入MongoDB数据库中。 最后,需要在命令行中运行Spider: ``` scrapy crawl xia_chu_fang ``` 这样,Spider就会开始爬取数据,并将数据存入MongoDB数据库中。
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值