Python 属性错误:';xml.etree.ElementTree.Element';对象没有属性';编码';
我试图制作一个桌面通知程序,为此我从一个网站上抓取新闻。当我运行程序时,我得到以下错误Python 属性错误:';xml.etree.ElementTree.Element';对象没有属性';编码';,python,xml,python-requests,Python,Xml,Python Requests,我试图制作一个桌面通知程序,为此我从一个网站上抓取新闻。当我运行程序时,我得到以下错误 news[child.tag]=child.encode('utf8') AttributeError:'xml.etree.ElementTree.Element'对象没有属性'encode' 我如何解决它?我对这个完全陌生。我试图寻找解决办法,但没有一个对我有效 这是我的密码: import requests import xml.etree.ElementTree as ET # url of n
news[child.tag]=child.encode('utf8')
AttributeError:'xml.etree.ElementTree.Element'对象没有属性'encode'
我如何解决它?我对这个完全陌生。我试图寻找解决办法,但没有一个对我有效
这是我的密码:
import requests
import xml.etree.ElementTree as ET
# url of news rss feed
RSS_FEED_URL = "http://www.hindustantimes.com/rss/topnews/rssfeed.xml"
def loadRSS():
'''
utility function to load RSS feed
'''
# create HTTP request response object
resp = requests.get(RSS_FEED_URL)
# return response content
return resp.content
def parseXML(rss):
'''
utility function to parse XML format rss feed
'''
# create element tree root object
root = ET.fromstring(rss)
# create empty list for news items
newsitems = []
# iterate news items
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.encode('utf8')
newsitems.append(news)
# return news items list
return newsitems
def topStories():
'''
main function to generate and return news items
'''
# load rss feed
rss = loadRSS()
# parse XML
newsitems = parseXML(rss)
return newsitems
您正在尝试将
str
转换为字节
,然后将这些字节存储在字典中。
问题是,你这样做的对象是一个
,
不是一个str
您可能想从该元素内部或周围获取文本,然后encode()
。
医生
建议使用
方法:
这将计算为一个str
,然后您可以encode()
请注意
可能不包含文本
(重点加上):
它们的值通常是字符串,但可以是任何特定于应用程序的对象
如果要使用这些属性,则必须处理None
或非字符串值:
head = '' if child.text is None else str(child.text)
tail = '' if child.text is None else str(child.text)
# Do something with head and tail...
即使这样也不够。
如果文本
或尾部
包含一些意外的字节
对象
(或完全错误)
编码时,这将引发一个UnicodeEncodeError
字符串与字节
我建议将文本保留为str
,而不进行编码。
将文本编码为字节
对象是将其写入二进制文件、网络套接字或其他硬件之前的最后一步
有关字节和字符之间差异的更多信息,请参阅Ned Batchelder的
""
(36分钟)。
他涵盖了Python 2和Python 3
示例输出
使用child.itertext()
方法,而不是对字符串进行编码,我从topStories()
获得了一个外观合理的词典列表:
我没有使用过xml,但错误表明
child
不是字符串对象。因此,在encode
之前,它似乎将您的元素
实例child
转换为一些字符串。简单地检查一下,child.text.encode
怎么样?是的,我也这样做了,但我得到了相同的错误@Leonard2news[child.tag]=child.text.encode('utf8')AttributeError:'NoneType'对象没有属性'encode',我想这个问题可能与数据有关。我的意思是,这取决于每个子
是否有一些文本。当我只写child.text时,我在通知程序消息中会出现以下错误。append(signature=signature,*args)TypeError:应为字符串或unicodeobject@ani:我没有看到消息。请将附加到代码中的任何位置。无论如何,正如我在回答中强调的,text
和tail
可以包含任何对象,所以不要假设它们是任何形式的文本,更不用说Unicode字符串了。(如果您确实获得了str
字符串,然后使用encode()
方法将它们转换为字节
,请参阅我关于将它们保留为字符串的更新。)否,我在使用str(child.text)时在另一个程序中使用message.append我收到以下错误UnicodeCodeError:“ascii”编解码器无法对136:ordinal不在范围(128)中的字符u'\u201c'进行编码@ani:还记得说“可能是任何特定于应用程序的对象”的位吗?这包括未指定(可能不正确)编码中的“文本”。您确定无法从itertext()
获取所需内容吗?我添加了一个从中获得的输出示例。
head = '' if child.text is None else str(child.text)
tail = '' if child.text is None else str(child.text)
# Do something with head and tail...
[
...,
{'description': 'Ayushmann Khurrana says his five-year Bollywood journey has '
'been “a fun ride”; adds success is a lousy teacher while '
'failure is “your friend, philosopher and guide”.',
'guid': 'http://www.hindustantimes.com/bollywood/i-am-a-hardcore-realist-and-that-s-why-i-feel-my-journey-has-been-a-joyride-ayushmann-khurrana/story-KQDR7gMuvhD9AeQTA7tbmI.html',
'link': 'http://www.hindustantimes.com/bollywood/i-am-a-hardcore-realist-and-that-s-why-i-feel-my-journey-has-been-a-joyride-ayushmann-khurrana/story-KQDR7gMuvhD9AeQTA7tbmI.html',
'media': 'http://www.hindustantimes.com/rf/image_size_630x354/HT/p2/2017/06/26/Pictures/actor-ayushman-khurana_24f064ae-5a5d-11e7-9d38-39c470df081e.JPG',
'pubDate': 'Mon, 26 Jun 2017 10:50:26 GMT ',
'title': "I am a hardcore realist, and that's why I feel my journey "
'has been a joyride: Ayushmann...'},
]