1

Scrapy + MongoDB (PyMongo) で Spider をクロールしようとしていますが、エラーが発生しました: 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
4

2 に答える 2

3

localhost ポート 27017 に接続するつもりだったようですが、代わりにこれらの値をキーとして使用して設定から値を取得しています。代わりにこれを意味しましたか?

 def __init__(self):
    self.server = 'localhost'
    self.port = '27017'
    self.db = 'IngressoRapido'
    self.col = 'Shows'
于 2013-08-29T17:11:48.697 に答える
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

于 2016-06-16T08:29:35.980 に答える