如何在Scrapy爬虫中获取管道对象
我用mongodb来存储爬虫抓取的数据。
现在我想查询一下数据的最后日期,这样我就可以继续抓取数据,而不需要从网址列表的头开始重新抓取(网址是可以通过日期来确定的,比如:/2014-03-22.html)。
我只想要一个连接对象来进行数据库操作,这个对象是在管道中的。
所以,我想知道怎么才能在爬虫里获取到这个管道对象(而不是新建一个)。
或者,有没有更好的增量更新的解决方案...
提前谢谢你。
抱歉,我的英语不好...
现在就先这样:
# 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.
好吧,我就是不想新建一个对象....我承认我有强迫症..
2 个回答
1
根据scrapy的架构概述:
项目管道负责处理那些已经被爬虫提取(或抓取)出来的项目。
简单来说,就是先让scrapy的爬虫工作,然后提取出来的项目会进入管道处理,不能再回头。
一个可能的解决办法是在管道中检查你抓取的项目是否已经在数据库里。
另一个方法是把你爬取过的网址列表保存在数据库中,然后在爬虫里检查你是否已经从某个网址获取过数据。
因为我不太明白你说的“从头开始”是什么意思,所以无法给出具体的建议。
希望这些信息对你有帮助。
4
Scrapy的管道里有一个叫做 open_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会替代它。