ItemLoader add_value方法在某些字段上不起作用

2024-10-06 10:25:21 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在我的项目中使用scrapy的ItemLoader。问题是,它在某些字段中运行良好,而在其他字段中却不起作用

我正在ubuntu 16.04服务器上使用Scrapy 1.7.2/Python 3.7

class RealtyItem(Item):
...
price_for_sale = Field(input_processor=MapCompose(drop_currency), output_processor=TakeFirst())  # int
    price = Field(input_processor=MapCompose(drop_currency), output_processor=TakeFirst())  # int
    price_without_tax = Field(input_processor=MapCompose(drop_currency), output_processor=TakeFirst())  # int
    price_per_unit = Field(input_processor=MapCompose(drop_currency), output_processor=TakeFirst())  # int
    supplementary_charges = Field(input_processor=MapCompose(drop_currency), output_processor=TakeFirst()) # int
...

因此,有几个字段共享相同的处理器。 调试时,我可以看到只有supplementary_charges被处理并添加到项目中,而项目中缺少其他价格字段。看起来item.add_value(label, value)对5个价格字段中的4个没有任何作用。 这是我的密码:

    def parse_property(self, response):
        item = ItemLoader(item=RealtyItem(), response=response)

        details = response.xpath('//div[@class="flat-attributes__item"]')
        for record in details:
            label = record.xpath('./p[1]/text()').get().strip()
            if label not in self._ignore_fields:
                value = ''.join(record.xpath('./p[2]//text()').getall()).strip()
                if label in self._composite_fields:
                    for v in value.split(','):
                        l = self._property_title[v.strip()]
                        item.add_value(l, True)
                else:
                    label = self._property_title[label]
                    item.add_value(label, value)

标签取自硬编码字典:

 _property_title = {
        'Nebenkosten': 'supplementary_charges',
        'Bruttomiete (inkl. NK)': 'price',
        'Nettomiete (exkl. NK)': 'price_without_tax',
        'Fläche': 'living_space',
        'Balkon/Sitzplatz': 'balcony',
        'Anzahl Zimmer': 'rooms',
        'Aussicht': 'perspective',
        'Referenz': 'reference'
...
}

我很确定所有的价格都被适当地抹去了: parse values

但最后,当supplementary_charges和其他字段就位时,项目中缺少所有价格: after parsing

如果我一步一步地调试它, 我可以清楚地看到item.add_value调用后没有任何变化

我错过了什么或做错了什么


Tags: 项目selffieldinputoutputvalueitemprocessor