我正在尝试使用lxml.etree来解析Wordpress导出文档(它的XML,有点像RSS)。我只对已发布的帖子感兴趣,所以我使用以下内容来浏览已发布的帖子:
for item in data.findall("item"):
if item.find("wp:post_type").text != "post":
continue
if item.find("wp:status").text != "publish":
continue
write_post(item)
其中data
是标记,其中包含所有item
标记。item
标记包含帖子,页面和草稿。我的问题是lxml无法找到名称中包含:
的标记(例如wp:post_type
)。当我尝试item.find("wp:post_type")
时,我收到此错误:
Traceback (most recent call last):
File "<input>", line 1, in <module>
File "lxml.etree.pyx", line 1279, in lxml.etree._Element.find (src/lxml/lxml.e
tree.c:38124)
File "/usr/lib64/python2.7/site-packages/lxml/_elementpath.py", line 210, in f
ind
it = iterfind(elem, path)
File "/usr/lib64/python2.7/site-packages/lxml/_elementpath.py", line 200, in i
terfind
selector = _build_path_iterator(path)
File "/usr/lib64/python2.7/site-packages/lxml/_elementpath.py", line 184, in _
build_path_iterator
selector.append(ops[token[0]](_next, token))
KeyError: ':'
我假设KeyError : ':'
指的是标签名称中的冒号无效。有什么方法可以逃脱冒号,以便lxml找到正确的标签? :
在这种情况下是否具有某些特殊含义?或者我做错了什么?任何帮助将不胜感激。
答案 0 :(得分:9)
:
是XML命名空间分隔符。要在lxml中转义冒号,您需要将其替换为大括号内的命名空间URL,如item.find("{http://example.org/}status").text
中所示。