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

使用Python ElementTree按属性值查找属性,python,xml,xpath,Python,Xml,Xpath,给定以下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> 然而,这只给了我: Attri

给定以下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>
然而,这只给了我:

AttributeError:“非类型”没有属性“属性”


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

import xml.etree.ElementTree as ER

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

您的代码对我有效(除了
println
NoneType
表示
find()
找不到元素-可能您使用了不同的路径或不同的xml。对我也适用。你确定这是整个XML数据吗?D**n,我复制了错误的片段。XML包含在应用XPath时需要考虑的名称空间。它是这样工作的。
import xml.etree.ElementTree as ER

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