繁体   English   中英

使用Python ElementTree按属性值查找属性

[英]Finding attribute by attribute value with Python ElementTree

给定以下XML:

<Services total="3">
    <link href="http://localhost/service1" rel="s1"/>
    <link href="http://localhost/service2" rel="s2"/>
    <link href="http://localhost/service3" rel="s3"/>
</Services>

使用Python我想查找rel="s2"href属性。 这是我当前的代码:

doc = ER.fromstring(xml)
href = doc.find(".//link[@rel='s2']").attrib['href']
println(href)

但是,这只会给我:

AttributeError:'NoneType'没有属性'attrib'

xml路径中存在一些语法错误。 尝试以下代码:

import xml.etree.ElementTree as ER

doc = ER.fromstring(xml)
href = doc.find(".//link/.[@rel='s2']")
print(href)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM