2016-09-18 40 views
2

我有一個管道,將數據發佈到webhook。我想重新使用它作爲另一個蜘蛛。我的管道是這樣的:是否可以在scrapy中動態創建管道?

class Poster(object): 
    def process_item(self, item, spider): 
     item_attrs = { 
      "url": item['url'], "price": item['price'], 
      "description": item['description'], "title": item['title'] 
     } 

     data = json.dumps({"events": [item_attrs]}) 

     poster = requests.post(
      "http://localhost:3000/users/1/web_requests/69/supersecretstring", 
      data = data, headers = {'content-type': 'application/json'} 
     ) 

     if poster.status_code != 200: 
      raise DropItem("error posting event %s code=%s" % (item, poster.status_code)) 

     return item 

事情是,在另一個蜘蛛,我需要張貼到另一個網址,並有可能使用不同的屬性。是否可以指定這個代替:

class Spider(scrapy.Spider): 
    name = "products" 
    start_urls = (
     'some_url', 
    ) 
    custom_settings = { 
     'ITEM_PIPELINES': { 
      'spider.pipelines.Poster': 300, 
     }, 
    } 

類似:

custom_settings = { 
     'ITEM_PIPELINES': { 
      spider.pipelines.Poster(some_other_url, some_attributes): 300, 
     }, 
    } 

我知道當我創建的蜘蛛,我需要的URL,以及我將提取的字段。

回答

3

這樣做的方法很少,但最簡單的方法是在您的管道中使用open_spider(self, spider)。用例的

例子:

scrapy crawl myspider -a pipeline_count=123

然後設置管道閱讀:

class MyPipeline(object): 
    count = None 

    def open_spider(self, spider): 
     count = getattr(spider, 'pipeline_count') 
     self.count = int(count) 

    # or as starrify pointed out in the comment below 
    # access it directly in process_item 
    def process_item(self, item, spider): 
     count = getattr(spider, 'pipeline_count') 
     item['count'] = count 
     return item 
    <...> 
+1

LGTM。只是想指出'def process_item(self,item,spider):'中已經有一個'spider'實例,並且你甚至不需要'open_spider'方法來獲取一些蜘蛛屬性:) – starrify

+0

Oh right !雖然'open_spider'更適合創建有狀態參數,如果你的參數是無狀態的,那麼使用'process_item'肯定會更聰明! – Granitosaurus

相關問題