[英]How to get the pipeline object in Scrapy spider
我使用mongodb來存儲抓取的數據。
現在我想查詢數據的最后日期,我可以繼續抓取數據而不需要從url列表的開頭重新啟動它。(url,可以通過日期確定,如:/ 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.
好的,只是不想新建一個新對象....我承認我是一個OCD ..
Scrapy Pipeline有一個open_spider方法,在初始化蜘蛛之后執行。 您可以將對數據庫連接,get_date()方法或Pipeline本身的引用傳遞給您的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):
....
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在初始化后替換它。
根據scrapy 架構概述 :
物品管道負責在物品被蜘蛛提取(或刮除)后處理物品。
基本上這意味着,首先,scrapy蜘蛛正在工作,然后提取的物品進入管道 - 無法倒退。
一種可能的解決方案是,在管道本身中,檢查您已刮取的項目是否已存在於數據庫中。
另一種解決方法是保留您在數據庫中抓取的網址列表,並在蜘蛛中檢查您是否已從網址獲取數據。
既然我不確定你從“從頭開始”是什么意思 - 我不能提出具體的建議。
希望至少這些信息有所幫助。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.