null
null

Reputation: 1217

Scrapy: How to initialize item with None?

For example, the item in scrapy is:

class CrawlerItem(scrapy.Item):

    name = scrapy.Field()

    country = scrapy.Field()

    title = scrapy.Field()

    subject = scrapy.Field()

    ......
item = CrawlerItem()

How could I initialize all of the fields value of item with None?

I could do this with:

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

But the problem is, there're far two many fields. Are there any methods that could do:? item.set_all(None)

Upvotes: 2

Views: 929

Answers (1)

Tarun Lalwani
Tarun Lalwani

Reputation: 146560

You just need to iterate through self.fields in the items class

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

And then in your code you can call

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

Upvotes: 4

Related Questions