user2492364
user2492364

Reputation: 6713

how to check the value is empty in Item()?

I have a item = Item()
and I want to check if it's empty,but with error.
I think it's because item['mvid'] is empty
so how can I check this???
try except??

    if not item['mvid'] :
        log.msg("title={}".format(item['title']) ,level=log.WARNING)


    if not item['mvid'] :
  File "/Users/some/djangoenv/lib/python2.7/site-packages/scrapy/item.py", line 50, in __getitem__
    return self._values[key]
exceptions.KeyError: 'mvid'

Upvotes: 1

Views: 75

Answers (2)

PikeSZfish
PikeSZfish

Reputation: 109

I think you can do: if item.get("mvid", None): # do something

Upvotes: 0

Gohn67
Gohn67

Reputation: 10648

The ValueError here means that the key 'mvid' was never set in your dict. This is different than if item['mvid'] was set to None or an empty string for example.

You can do:

if 'mvid' not in item:
    # Do something

Depending on your use case, an alternate approach could be to catch the exception:

try:
   print item['mvid']
except ValueError:
   # Handle error

Upvotes: 2

Related Questions