【问题标题】:Tags with : in name in lxml带有 : 在 lxml 中的名称的标签
【发布时间】:2011-07-05 07:32:44
【问题描述】:

我正在尝试使用 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 找到正确的标签? : 在这种情况下有什么特殊含义吗?还是我做错了什么?任何帮助将不胜感激。

【问题讨论】:

    标签: python xml wordpress lxml elementtree


    【解决方案1】:

    : 是一个 XML 命名空间分隔符。要在 lxml 中转义冒号,您需要将其替换为大括号内的命名空间 URL,如 item.find("{http://example.org/}status").text。

    【讨论】:

      猜你喜欢
      • 2012-04-22
      • 2020-10-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-01-10
      • 2011-02-20
      • 2020-08-17
      • 1970-01-01
      相关资源
      最近更新 更多