错误在Python中遍历xml

时间:2015-09-29 17:53:35

标签: python xml

我尝试遍历从网址检索到的xml文件始终失败。但是,如果我直接在代码中输入xml文件,它会起作用,例如:

    smplexml = ''' somexml'''

但我没有成功制作如下代码:

    import xml.etree.ElementTree as ET
    import urllib

    xmlstr = urllib.urlopen('http://www.w3schools.com/xml/simple.xml').read()
    tree = ET.fromstring(xmlstr)
    print tree.find('name').text
这项工作。请问我做错了什么?有时我会收到如下错误消息:

    AttributeError: 'NoneType' object has no attribute 'text'

1 个答案:

答案 0 :(得分:0)

import xml.etree.ElementTree as ET
import urllib

xmlstr = urllib.urlopen('http://www.w3schools.com/xml/simple.xml').read()
tree = ET.fromstring(xmlstr)
for food in tree:
    print food.find('name').text