ElementTree 和命名空间查找
我有一个有效的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
的格式来找到带命名空间的元素呢?
1 个回答
5
你应该指定 namespaces
参数:
namespaces = {'html': 'http://www.w3.org/1999/xhtml'}
root.find('html:head', namespaces=namespaces)
另外可以参考: