Python: 从与其他元素同名的自闭合元素中提取属性

Python: Extract attributes from a self-closing element with same name as other elements

我需要从一些 XML 包含的同名元素中提取一些属性值(抱歉,我不太了解 XML 术语)。

我一直在使用 xml.etree.ElementTree 库进行 xpath 解析,但我总是得到空值。

这是 XML 的示例:

<parent>
 <child tag1="spam" tag2="1" tag3="some url" />
 <child tag1="spam" tag2="2" tag3="another url" />
 <child tag1="spam" tag2="3" tag3="yet another url" />
 <child tag1="spam" tag2="4" tag3="the last url" />

我正在尝试从第 3 个子标签中提取 url,其中 tag2="3"

import xml.etree.ElementTree as ET

r=requests.get(url, user, password) #from another .py file I made for this use
tree=ET.fromstring(r.content)
desired_out=tree.findall('.//child/..[@tag2="3"]')
print(desired_out)

当我尝试提取它时,requests.get 执行适用于 XML 中的所有其他字段,但我似乎遇到了一些 xpath 问题。

预期输出应该是 URL,或者至少是它存储在内存中的一些指示,而不是我得到 [].

感谢您的帮助。


我整理好了。无论出于何种原因,xpath 选项对我不起作用,所以我只做了几个 for 循环和一个 if 语句来获得我需要的东西。

```python
for lmnt in root.findall(parent, namespace):
    for grandchild in lmnt.findall(child, namespace):
        tags = grandchild.attrib[tag2_attrib]
            if tags == '3':
                url = grandchild.attrib[tag3_attrib]
```

returns 字符串格式的 URL。感谢您的回复,感谢您的回复。

使用这个 xpath

.//child[@tag2="3"]/@tag3

另一种方法是将 XML 转换为 dict xmltodict:

import xmltodict

data = '''<parent>
 <child tag1="spam" tag2="1" tag3="some url" />
 <child tag1="spam" tag2="2" tag3="another url" />
 <child tag1="spam" tag2="3" tag3="yet another url" />
 <child tag1="spam" tag2="4" tag3="the last url" />
</parent>'''

result = xmltodict.parse(data)['parent']['child'][2]['@tag3']

输出:

yet another url