只是返回xpath中的元素文本(python/lxml) [英] Just returning the text of elements in xpath (python / lxml)
本文介绍了只是返回xpath中的元素文本(python/lxml)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个像这样的XML结构:
I have an XML structure like this:
mytree = """
<path>
<to>
<nodes>
<info>1</info>
<info>2</info>
<info>3</info>
</nodes>
</to>
</path>
"""
我目前在python lxml中使用xpath来获取节点:
I'm currently using xpath in python lxml to grab the nodes:
>>> from lxml import etree
>>> info = etree.XML(mytree)
>>> print info.xpath("/path/to/nodes/info")
[<Element info at 0x15af620>, <Element info at 0x15af940>, <Element info at 0x15af850>]
>>> for x in info.xpath("/path/to/nodes/info"):
print x.text
1
2
3
这很棒,但是有没有一种更干净的方法来将 just 内部文本作为列表,而不必随后编写for循环?
像这样:
This is great, but is there a cleaner way to grab just the internal texts as a list, rather than having to write the for-loop afterwards?
Something like:
print info.xpath("/path/to/nodes/info/text")
(但这不起作用)
推荐答案
您可以使用:
print info.xpath("/path/to/nodes/info/text()")
这篇关于只是返回xpath中的元素文本(python/lxml)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文