0

我是 ItemLoaders 的新手。我有一个集合seen_ids,我在其中添加了所有product_ids我抓取的内容,以便我可以检查是否有任何重复并尽早跳过它。

问题是,我想在__init__. 如果它是重复的,我不希望返回任何引用,并且我不能明确地从__init__. 我该怎么做?

seen_ids = set()

def __init__(self, item=None, selector=None, response=None, parent=None, product_id=None, **context):
    if product_id in self.seen_ids:
        return None

    self.seen_ids.add(product_id)
    super(GarmentLoader, self).__init__(item, selector, response, parent, **context)
    item['retailer_sku'] = product_id

但是它在 None 上给出错误,如果我不返回任何东西,它会返回对象的引用并且进一步的检查失败。

4

1 回答 1

0

它不起作用,因为构造函数基本上不返回除了实例之外的任何东西,而且实例不会共享 see_ids。

您可以改用类方法:

class CustomItemLoader(ItemLoader):
    seen_ids = set()

    @classmethod
    def with_product_id(cls, **kwargs):
        product_id = kwargs.pop('product_id', None)
        if product_id in cls.seen_ids:
            return None
        cls.seen_ids.add(product_id)
        return cls(**kwargs)

然后使用它创建加载程序的实例:

loader = CustomItemLoader.with_product_id(response=response, product_id=product_id, ...)
于 2018-11-05T23:06:27.317 回答