首页 > 解决方案 > Python 从 xhtml:link 抓取属性值

问题描述

我正在尝试从 href 属性中收集值。我以前做过这个,但似乎无法让它为“xhtml:link”工作。

我试过以下方法:

import xml.etree.ElementTree as ET
root = ET.parse('items.xml').getroot()

for type_tag in root.findall('xhtml:link'):
    value = type_tag.get('href')
    print(value)

和xml

<?xml version="1.0" encoding="UTF-8"?>
<url>
    <loc>https://www.example.com</loc>
    <xhtml:link rel="alternate" href="https://www.example.com"></xhtml:link>
    <xhtml:link rel="alternate" href="https://www.example.com/"></xhtml:link>
    <xhtml:link rel="alternate" href="https://www.example.com/"></xhtml:link>
    <xhtml:link rel="alternate" href="https://www.example.com/"></xhtml:link>
    <xhtml:link rel="alternate" href="https://www.example.com/"></xhtml:link>
    <xhtml:link rel="alternate" href="https://www.example.com/"></xhtml:link>
</url>

我试图找到这背后的原因,但似乎找不到任何东西。任何建议都会非常感谢。

标签: pythonxmlpython-3.x

解决方案


xhtmlnamespaces=是一个命名空间,它需要选项findall()

第一:我必须添加xmlns:xhtml="your namespace"才能运行它 - 可能你也有它。

我不得不在findall()

text = '''<?xml version="1.0" encoding="UTF-8"?>
<url xmlns:xhtml="your namespace">
    <loc>https://www.example.com</loc>
    <xhtml:link rel="alternate" href="https://www.example.com"></xhtml:link>
    <xhtml:link rel="alternate" href="https://www.example.com/"></xhtml:link>
    <xhtml:link rel="alternate" href="https://www.example.com/"></xhtml:link>
    <xhtml:link rel="alternate" href="https://www.example.com/"></xhtml:link>
    <xhtml:link rel="alternate" href="https://www.example.com/"></xhtml:link>
    <xhtml:link rel="alternate" href="https://www.example.com/"></xhtml:link>
</url>'''

import xml.etree.ElementTree as ET
root = ET.fromstring(text)#.getroot()

for type_tag in root.findall('xhtml:link', namespaces={'xhtml':'your namespace'}):
    value = type_tag.get('href')
    print(value)

我不知道是否有忽略名称空间的功能。


推荐阅读