Using cElementTree to parse attributes

◇◆丶佛笑我妖孽 提交于 2019-12-23 05:01:39

问题


I am learning cElementTree and my XML looks like this.... I am trying to obtain the "updated" text ( which I can! ) and the attribute value of "href" in the "link" node ( which I can't ).

<feed>
    <entry>
        <link href="http://www.mondocars.com/0001127602.htm"/>
        <updated>2017-04-19T13:10:24-04:00</updated>
    </entry>
</feed>

My code to parse it looks like this...

for entry in root.findall('entry'):
    updated = entry.find('updated').text
    print updated
    for link in root.findall('link'):
        href = link.get('href').attrib
        print updated, href

href value isn't being pulled at all. I am convinced that it's probably an unnecessary 2nd for loop. updated populates fine but I can't figure out how to get the href value. Anyone encounter this?

Many thanks in advance. Janie


回答1:


for entry in root.findall('entry'):         
    updated = entry.find('updated').text
    href = entry.find('link').attrib.get('href')
    print updated,href

is the correct way.



来源:https://stackoverflow.com/questions/43503971/using-celementtree-to-parse-attributes

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!