lxml.etree没有返回正确的xpath值

时间:2014-04-06 02:44:00

标签: python xpath lxml

我有一个像这样的xml字符串

<description> asdasdasd <a> Item1 </a><a> Price </a></description>

我正在使用lxml.etree,如下所示:

import lxml.etree as le
doc=le.fromstring("<description>asdasdasd <a>Item1</a> <a>Price</a> </description>")
desc = doc.xpath("//description")[0]
print desc.text

desc.text仅返回 asdasdasd 。我期待asdasdasd Item1 Price。我的代码有问题吗?

3 个答案:

答案 0 :(得分:0)

这是一种方法:

print desc.text + ' '.join(child.text for child in desc)

打印:

asdasdasd Item1 Price

答案 1 :(得分:0)

另一种选择是使用descendant-or-self xpath技巧:

desc = doc.xpath("//description/descendant-or-self::*")
print ' '.join(child.text for child in desc)

打印:

asdasdasd  Item1 Price

答案 2 :(得分:0)

不,你必须看到它是一棵树(这就是为什么lxml.etree

根据定义,xml节点可以在其中包含文本和一些属性以及其他节点(参见this

|--> description
      |--> a
      |--> a

也许这有助于理解:

import lxml.etree as le
doc=le.fromstring("<description>asdasdasd <a>Item1</a> <a>Price</a> </description>")
desc = doc.xpath("//description")[0]
print desc.text
for child in desc:
  print child.text

输出:

asdasdasd 
Item1
Price

XML背后的想法是尝试对实例进行建模(或多或少)。在您的情况下,您有一个description对象,其中包含两个a个对象(例如,可以是一个列表)