我有和这个问题一样的问题,但我很难让它发挥作用。
我想得到<itunes:subtitle>
的所有值。不要与自闭标签<itunes:subtitle/>
混淆。
这是我在sample.xml
:中的XML数据
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<rss version="2.0" xmlns:itunes="http://www.itunes.com/dtds/podcast-1.0.dtd" xmlns:content="http://purl.org/rss/1.0/modules/content/">
<channel>
<item>
<title>A title</title>
<itunes:subtitle/>
<itunes:subtitle>A subtitle</itunes:subtitle>
</item>
<item>
<title><![CDATA[Another title]]></title>
<itunes:subtitle/>
<itunes:subtitle>Yet another subtitlen</itunes:subtitle>
</item>
</channel>
</rss>
import xml.etree.ElementTree as ET
with open('sample.xml', 'r', encoding='utf8') as f:
tree = ET.parse(f)
root = tree.getroot()
for xml_item in root.iter('item'):
namespaces = {'itunes': 'subtitle'}
print(root.findall('itunes:subtitle', namespaces))
但是,这会返回空列表。
[]
[]
在另一个9岁的问题或Stackoverflow上的其他地方,我找不到任何有意义的帮助。请帮帮我。
首先,查看<rss>
元素中声明的名称空间:
<rss version="2.0"
xmlns:itunes="http://www.itunes.com/dtds/podcast-1.0.dtd"
xmlns:content="http://purl.org/rss/1.0/modules/content/">
别名itunes
指的是名称空间http://www.itunes.com/dtds/podcast-1.0.dtd
,别名content
指的是名字空间http://purl.org/rss/1.0/modules/content/
。
在Python代码中,namespaces
字典需要反映这些映射,因此:
namespaces = {'itunes': 'http://www.itunes.com/dtds/podcast-1.0.dtd'}
第二,从文件::
Element.findall()
只查找带有标记的元素,这些元素是当前元素的直接子元素。
在循环中。。。
for xml_item in root.iter('item'):
print(root.findall('itunes:subtitle', namespaces))
您的循环变量是xml_item
,但您在root
上调用findall
,并且<itunes:subtitle>
元素不是rss
标记的直接子元素。您需要:
for xml_item in root.iter('item'):
print(xml_item.findall('itunes:subtitle', namespaces))
给我们:
import xml.etree.ElementTree as ET
with open('sample.xml', 'r', encoding='utf8') as f:
tree = ET.parse(f)
root = tree.getroot()
namespaces = {'itunes': 'http://www.itunes.com/dtds/podcast-1.0.dtd'}
for xml_item in root.iter('item'):
print(xml_item.findall('itunes:subtitle', namespaces))
运行以上代码生成:
[<Element '{http://www.itunes.com/dtds/podcast-1.0.dtd}subtitle' at 0x7fb46ab48770>, <Element '{http://www.itunes.com/dtds/podcast-1.0.dtd}subtitle' at 0x7fb46ab487c0>]
[<Element '{http://www.itunes.com/dtds/podcast-1.0.dtd}subtitle' at 0x7fb46ab488b0>, <Element '{http://www.itunes.com/dtds/podcast-1.0.dtd}subtitle' at 0x7fb46ab48900>]