例如,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)
答案 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)