如何在Scrapy Spider中获取管道对象
问题内容:
我已经使用 mongodb 来存储爬网的数据。
现在我想查询数据的最后日期,这样我就可以继续抓取数据而无需从url列表的开头重新启动它。(url可以由日期确定,例如:/ 2014-03-22 .html)
我只希望一个连接对象执行数据库操作,该操作正在管道中。
因此,我想知道如何在Spider中获取管道对象(不是新对象)。
或者,任何更好的增量更新解决方案…
提前致谢。
抱歉,我的英语不好…现在就试用:
# This is my Pipline
class MongoDBPipeline(object):
def __init__(self, mongodb_db=None, mongodb_collection=None):
self.connection = pymongo.Connection(settings['MONGODB_SERVER'], settings['MONGODB_PORT'])
....
def process_item(self, item, spider):
....
def get_date(self):
....
和蜘蛛:
class Spider(Spider):
name = "test"
....
def parse(self, response):
# Want to get the Pipeline object
mongo = MongoDBPipeline() # if take this way, must a new Pipeline object
mongo.get_date() # In scrapy, it must have a Pipeline object for the spider
# I want to get the Pipeline object, which created when scrapy started.
好吧,就是不想新的对象。…我承认我是强迫症。
问题答案:
Scrapy管道具有open_spider方法,该方法将在初始化Spider之后执行。您可以将对数据库连接的引用,get_date()方法或管道本身传递给蜘蛛。后者与您的代码的一个示例是:
# This is my Pipline
class MongoDBPipeline(object):
def __init__(self, mongodb_db=None, mongodb_collection=None):
self.connection = pymongo.Connection(settings['MONGODB_SERVER'], settings['MONGODB_PORT'])
....
def process_item(self, item, spider):
....
def get_date(self):
....
def open_spider(self, spider):
spider.myPipeline = self
然后,在蜘蛛中:
class Spider(Spider):
name = "test"
def __init__(self):
self.myPipeline = None
def parse(self, response):
self.myPipeline.get_date()
我认为此__init__()
方法不是必需的,但我将其放在此处以表明open_spider在初始化后将其替换。