【问题标题】:Python: Extract attributes from a self-closing element with same name as other elementsPython:从与其他元素同名的自闭合元素中提取属性
【发布时间】:2019-08-23 08:47:48
【问题描述】:

我需要从一些包含同名元素的 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" />

我正在尝试从第三个子标签中提取 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]
```

以字符串格式返回 URL。不过感谢您的回复,感谢您的回复。

【问题讨论】:

    标签: python xml xpath elementtree


    【解决方案1】:

    使用这个 xpath

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

    【讨论】:

    • 我试过这个但得到一个错误“SyntaxError: cannot use absolute path on element”
    【解决方案2】:

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

    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
    

    【讨论】:

    • 谢谢,但我不想要 tag2 的值,我想要 tag2 后面的 URL。它也是来自网页/API 调用的 XML,而不是文件,但我会看看是否可以通过调整您的代码以适应它。
    猜你喜欢
    • 1970-01-01
    • 2017-08-13
    • 1970-01-01
    • 2018-10-20
    • 1970-01-01
    • 1970-01-01
    • 2017-03-16
    • 2012-03-15
    • 1970-01-01
    相关资源
    最近更新 更多