lxml中名称带:的标签

5 投票
1 回答
3770 浏览
提问于 2025-04-16 12:37

我正在尝试使用 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 找到正确的标签,或者说我需要怎么处理这个冒号?在这个情况下,: 有特别的含义吗?如果有人能帮忙,我会很感激。

1 个回答

9

这个:是用来区分XML命名空间的符号。如果你在使用lxml的时候想要处理这个冒号,就需要用大括号把命名空间的URL包起来,比如这样写:item.find("{http://example.org/}status").text

撰写回答