【发布时间】:2016-08-17 21:42:58
【问题描述】:
我正在解析位于此链接的 XML:
我需要访问节点内的数据,似乎我编写的程序告诉我节点内没有任何内容。这是我的代码:
import urllib
import xml.etree.ElementTree as ET
#prompt for link where xml data resides
#Use this link for testing: http://python-data.dr-chuck.net/comments_42.xml
url = raw_input('Enter URL Link: ')
#open url and prep for parsing
data = urllib.urlopen(url).read()
#read url data and convert to XML Node Tree for parsing
comments = ET.fromstring(data)
#the comment below is part of another approach to the solution
#both approaches are leading me into the same direction
#it appears as if the data inside the node is not being parsed/extracted
#counts = comments.findall('comments/comment/count')
for count in comments.findall('count'):
print comments.find('count').text
当我单独打印出“数据”变量时,我得到了完整的 XML 树。但是,当我尝试访问特定节点内的数据时,该节点返回为空。
我还尝试打印以下代码以查看我会返回哪些数据:
for child in comments:
print child.tag, child.attrib
我得到的输出是:
注意 {} 厘米 {}
我做错了什么,我错过了什么?
我在尝试访问节点的不同循环策略时遇到的错误之一是:
Traceback (most recent call last):
File "xmlextractor.py", line 16, in <module>
print comments.find('count').text
AttributeError: 'NoneType' object has no attribute 'text'
请帮忙,谢谢!!!
更新:
在查看 python 的 etree 文档时,我意识到我的方法一直在尝试“获取”节点属性而不是节点的内容。我还没有找到答案,但我肯定更接近了!!!
第二次更新:
所以我尝试了这段代码:
import urllib
import xml.etree.ElementTree as ET
#prompt for link where xml data resides
#Use this link for testing: http://python-data.dr-chuck.net/comments_42.xml
url = raw_input('Enter URL Link: ')
#open url and prep for parsing
data = urllib.urlopen(url).read()
#read url data and convert to XML Node Tree for parsing
comments = ET.fromstring(data)
counts = comments.findall('comments/comment/count')
print len(counts)
for count in counts:
print 'count', count.find('count').text
从上面,当我运行这段代码时:
print len(counts)
输出我的计数列表中有 50 个节点,但我仍然收到相同的错误:
Traceback (most recent call last):
File "xmlextractor.py", line 18, in <module>
print 'count', count.find('count').text
AttributeError: 'NoneType' object has no attribute 'text'
我不明白为什么当我尝试访问节点的内容时它说没有“文本”属性。
我做错了什么??
【问题讨论】:
-
我添加了用于测试的 XML 文件所在的特定链接...
标签: python xml xml-parsing string-parsing