我是一个完全的初学者,在尝试使用Python从URL打开XML文件时遇到一些问题。
下面是我的代码(我在网上找到的一段代码):
# import library to do http requests:
from urllib.request import urlopen
#import easy to use xml parser called minidom:
from xml.dom.minidom import parseString
#all these imports are standard on most modern python implementations
#download the file:
file = urlopen('http://www.odaa.dk/storage/f/2014-04-28T12%3A49%3A26.677Z/lejemaal.xml')
#convert to string:
data = file.read()
#close file because we dont need it anymore:
file.close()
#parse the xml you downloaded
dom = parseString(data)
#retrieve the first xml tag (<tag>data</tag>) that the parser finds with name tagName:
xmlTag = dom.getElementsByTagName('tagName')[0].toxml()
#strip off the tag (<tag>data</tag> ---> data):
xmlData = xmlTag.replace('<tagName>', '').replace('</tagName>', '')
#print out the xml tag and data in this format: <tag>data</tag>
print(xmlTag)
#just print the data
print(xmlData)当我运行这段代码时,我得到一个错误消息:
Traceback (most recent call last):
File "/Users/-----/PycharmProjects/First/test.py", line 20, in <module>
xmlTag = dom.getElementsByTagName('tagName')[0].toxml()
IndexError: list index out of range在阅读了黑板上类似的帖子后,我似乎正在尝试访问一些不存在的东西。或者是因为我复制的代码片段写着"tagName"?我需要编辑这个吗?
我该如何解决我的问题?我甚至不确定我想要的结果是什么,因为我只是想让一些事情发生。希望有人能为我指明正确的方向:)
发布于 2014-07-03 22:51:27
事实上,您已经拥有的代码已经完成了这项工作(未经测试)。
问题是在xml文件中没有名为'tagName‘的标签,所以python会返回一个空的列表。
然后尝试获取这个空列表的第一个元素,即IndexError。
您应该尝试使用xml文档中存在的标记的名称来替换tagName。
您通常知道xml文件中有哪些标记,因为您知道它的结构。您还可以使用python通过以下代码以编程方式检索这些列表:
root = dom.documentElement
for node in root.childNodes:
print(node.tagName)这段代码应该输出文档根元素下所有节点的标记名(第一个节点包含所有其他节点)。
https://stackoverflow.com/questions/24553616
复制相似问题