python - 如何检查 Item() 中的值是否为空?

标签 python

我有一个item = Item()
我想检查它是否为空,但有错误。
我认为这是因为 item['mvid'] 为空
那么我该如何检查这个???
尝试除了??

    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'

最佳答案

这里的ValueError意味着你的字典中从未设置过键“mvid”。这与将 item['mvid'] 设置为 None 或空字符串等情况不同。

你可以这样做:

if 'mvid' not in item:
    # Do something

根据您的用例,另一种方法可能是捕获异常:

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

关于python - 如何检查 Item() 中的值是否为空?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27701041/

相关文章:

python - 在Django中,MyModel.objects.get(my_field=x)是否等于MyModel.objects.filter(my_field=x).get()?

python - 猴子补丁 __del__ 到新功能

Python ForkingTCPServer 错误

python - python中的数据结构 : maintaining filesystem structure within a database

Python程序无法导入点解析器

python - 如何将python应用程序连接到在线数据库

python - 是否可以在 TreeView 小部件中选择多行?

c++ - Boost::python:对象在重写的方法中自行销毁

python - 所有列表都在一个循环中,而不是具有单独列表的两个循环

python - Try, except 子句 with if, else