Python 是否可以在scrapy中动态创建管道?

Python 是否可以在scrapy中动态创建管道?,python,scrapy,Python,Scrapy,我有一个将数据发布到webhook的管道。我想再用它做另一只蜘蛛。我的管道是这样的: class Poster(object): def process_item(self, item, spider): item_attrs = { "url": item['url'], "price": item['price'], "description": item['description'], "title": item['title

我有一个将数据发布到webhook的管道。我想再用它做另一只蜘蛛。我的管道是这样的:

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
问题是,在另一个蜘蛛中,我需要发布到另一个url,并可能使用不同的属性。是否可以指定以下内容而不是此内容:

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,
        },
    }

我知道创建spider时需要的URL,以及要提取的字段。

实现这一点的方法很少,但最简单的方法是在管道中使用
open\u spider(self,spider)

用例示例:

scrapy crawl myspider-管道计数=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
    <...>
类MyPipeline(对象):
计数=无
def open_卡盘(自身、卡盘):
count=getattr(spider,“管道计数”)
self.count=int(count)
#或者正如starrify在下面的评论中指出的那样
#直接在进程项目中访问它
def过程_项目(自身、项目、蜘蛛):
count=getattr(spider,“管道计数”)
项目['count']=计数
退货项目

LGTM。只是想指出,
def process\u item(self,item,spider)中已经有一个
spider
实例:
,您甚至不需要一个
open\u spider
方法来仅仅检索一些spider属性:)哦,对了!虽然
open\u spider
更适合创建有状态的参数,但如果您的参数是无状态的,那么使用
process\u项
肯定更聪明!