Scrapy:如何使用None初始化项目?

时间:2017-09-22 04:35:21

标签: scrapy

例如,scrapy中的项目是:

class CrawlerItem(scrapy.Item):

    name = scrapy.Field()

    country = scrapy.Field()

    title = scrapy.Field()

    subject = scrapy.Field()

    ......
item = CrawlerItem()

如何使用None初始化item的所有字段值?

我可以这样做:

item['name'] = None
item['country'] = None
...

但问题是,有两个很多领域。有没有办法可以做到:? item.set_all(None)

1 个答案:

答案 0 :(得分:1)

您只需要在项目类

中迭代self.fields
class CrawlerItem(scrapy.Item):

    name = scrapy.Field()
    country = scrapy.Field()
    title = scrapy.Field()
    subject = scrapy.Field()

    def set_all(self, value):
        for keys, _ in self.fields.items():
            self[keys] = value

然后在您的代码中,您可以调用

item = CrawlerItem()
item.set_all(None)
print(item)