【问题标题】:Couldn' find element in XML by tag using LXML无法使用 LXML 通过标签在 XML 中查找元素
【发布时间】:2019-09-03 09:36:17
【问题描述】:

尝试使用Python 3.6.8 和LXML 4.4.1 解析data.xspf,并在this 之后找到<creator>Creator</creator> 元素但有[] 输出。

data.xspf

<?xml version="1.0" encoding="UTF-8"?>
<playlist xmlns="http://xspf.org/ns/0/" version="1">
  <title/>
  <creator/>
  <trackList>
    <track>
      <location>http://localhost:8000</location>
      <creator>Creator</creator>
      <title>Title</title>
      <annotation>Blah
Blah
Blah
Blah
Blah
Blah
Blah</annotation>
      <info>info</info>
    </track>
  </trackList>
</playlist>

脚本:

>>> from lxml import etree

>>> tree = etree.parse("data.xspf")
>>> tree.findall('.//creator')

有什么想法吗?

【问题讨论】:

  • 在您的示例中,创建者标签为空 (&lt;creator/&gt;)。出于测试目的,您可以尝试另一个节点:tree.findall('.//track')
  • @Stephan,我猜这种情况下的输出应该像&lt;lxml.etree._ElementTree object at 0x7fe91d8592c8&gt; 因为元素本身不是None。它包含的文本是空的。 tree.findall('.//track') -- 结果相同
  • 顺便说一下findall() 应该找到包括最后一个元素在内的所有元素

标签: python python-3.x lxml


【解决方案1】:

使用函数的第二个参数确保考虑到默认命名空间tree.findall('.//creator', { None : 'http://xspf.org/ns/0/' })。

【讨论】:

猜你喜欢
  • 2020-08-08
  • 2012-12-27
  • 2017-05-02
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-10-16
  • 2015-01-13
相关资源
最近更新 更多