【问题标题】:How to find element attribute using lxml如何使用lxml查找元素属性
【发布时间】:2012-02-17 20:13:20
【问题描述】:

假设我有以下 xml:

<package xmlns="http://example/namespace">
    <rating system="au-oflc">PG</rating>
    ...
</package>

要获取上述元素的文本,我正在执行以下操作:

from lxml import entree
f = open('/Users/David/Desktop/metadata.xml')
metadata_contents = f.read()
node = etree.fromstring(metadata_contents)
rating = node.xpath('//t:rating/text()', namespaces = {'t':'http://example/namespace'})
>>> rating
['PG']

如何获得“au-oflc”的值?

【问题讨论】:

    标签: python xml lxml


    【解决方案1】:

    您需要检索节点本身,而不是其文本:

    rating = node.xpath('//t:rating', namespaces = {'t':'http://example/namespace'})
    print rating[0].attrib['system']
    

    【讨论】:

      【解决方案2】:

      您还可以使用 XPath 访问该属性:

      system = node.xpath('//t:rating/@system', namespaces = {'t':'http://example/namespace'})
      print system[0]
      

      【讨论】:

        【解决方案3】:

        georganswer 假定所有rating 元素都将具有system 标记。如果不是这样,使用rating[0].attrib.get('system') 将避免 KeyError。

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 2012-12-27
          • 1970-01-01
          • 1970-01-01
          • 2013-05-15
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多