我有一个有效的xhtml文件。当我这样做的时候

import xml.etree.ElementTree as ET
print ET._namespace_map

它列出:
'http://www.w3.org/1999/xhtml': 'html'

当我这样做的时候:
root.find('{http://www.w3.org/1999/xhtml}head')

它发现:
<Element '{http://www.w3.org/1999/xhtml}head' at 0x104647168>

但当我这么做的时候:
root.find('html:head')

它抱怨道:
SyntaxError: prefix 'html' not found in prefix map

是否可以使用语法find找到一个名间隔元素ns:element

最佳答案

您应该指定namespaces参数:

namespaces = {'html': 'http://www.w3.org/1999/xhtml'}
root.find('html:head', namespaces=namespaces)

还可以看到:
Parsing XML with namespace in Python via 'ElementTree'

10-08 19:21