2017-07-26 69 views
0
for item in root.findall('./channel/item'): 
    news = {} 
    # iterate child elements of item 
    for child in item: 
     # special checking for namespace object content:media 
     if child.tag == '{http://search.yahoo.com/mrss/}content': 
      news['media'] = child.attrib['url'] 
     else: 
      news[child.tag] = child.text.encode('utf8') 
    newsitems.append(news) 

什么问题?我该如何解决这个问题?AttributeError:'NoneType'对象在python 2.7中没有属性'encode'

+0

这是因为'child.text'是'None'。过滤出来。 '如果child.text:...' –

回答

0

这里:

else: 
     news[child.tag] = child.text.encode('utf8') 

child.text在某些情况下None。所以不要在这种情况下创建字典条目,例如像这样:

elif child.text is not None: 
     news[child.tag] = child.text.encode('utf8') 
+0

谢谢!有效 –

相关问题