2013-08-29 27 views
0

我试图用scrapy + MongoDB(PyMongo)来抓取蜘蛛,我收到错误:名称必须是basestring的一个实例。PyMongo + Scrapy = name必须是basestring的一个实例

由于我的蜘蛛工作,因为它被刮的数据到JSON,我猜的错误是在我的新管道,这里是源代码:

import pymongo 

from scrapy import log 
from scrapy.conf import settings 
from scrapy.exceptions import DropItem 


class MongoDBPipeline(object): 
    def __init__(self): 
     self.server = settings['localhost'] 
     self.port = settings['27017'] 
     self.db = settings['IngressoRapido'] 
     self.col = settings['Shows'] 
     connection = pymongo.Connection(self.server, self.port) 
     db = connection[self.db] 
     self.collection = db[self.col] 

    def process_item(self, item, spider): 
     err_msg = '' 
     for banda, local in item.items(): 
      if not local : 
       err_msg += 'Faltando local %s da banda %s\n' % (banda, item['banda']) 
     if err_msg: 
      raise DropItem(err_msg) 
     self.collection.insert(dict(item)) 
     log.msg('Item written to MongoDB database %s/%s' % (self.db, self.col), 
     level=log.DEBUG, spider=spider) 
     return item 

回答

2

好像你的意思是连接到localhost端口27017,而是使用这些值作为从设置获取值的键。你的意思是呢?

def __init__(self): 
    self.server = 'localhost' 
    self.port = '27017' 
    self.db = 'IngressoRapido' 
    self.col = 'Shows' 
+0

新手上的错误,谢谢! –

+0

顺便说一句,现在我的收藏没有被创建,有什么建议,为什么? –

+0

只是疯狂的猜测:当你运行'mongo'时,你连接到'test'数据库。在你的情况下,你需要发出'使用IngressoRapido',然后才能在'show collections'的输出中看到你的'Shows'集合。 – cababunga

0

下面的代码完美地工作,并正确处理清理资源。可以使用from_crawler方法拉起设置。

class MongoPipeline(object): 
''' 
    Saves the scraped item to mongodb. 
''' 
def __init__(self, mongo_server, mongo_port, mongo_db, mongo_collection): 
    self.mongo_server = mongo_server 
    self.mongo_port = mongo_port 
    self.mongo_db = mongo_db 
    self.mongo_collection = mongo_collection 

@classmethod 
def from_crawler(cls, crawler): 
    return cls(
     mongo_server=crawler.settings.get('MONGODB_SERVER'), 
     mongo_port=crawler.settings.get('MONGODB_PORT'), 
     mongo_db=crawler.settings.get('MONGODB_DB'), 
     mongo_collection=crawler.settings.get('MONGODB_COLLECTION'), 
    ) 

def open_spider(self, spider): 
    self.client = pymongo.MongoClient(self.mongo_server, self.mongo_port) 
    self.db = self.client[self.mongo_db] 

def close_spider(self, spider): 
    self.client.close() 

def process_item(self, item, spider): 
    self.db[self.mongo_collection].insert(dict(item)) 
    return item 

注意:请在piplines.py中导入pymongo。

请检查相同的官方文档。 http://doc.scrapy.org/en/latest/topics/item-pipeline.html#write-items-to-mongodb

相关问题