Just returning the text of elements in xpath (python / lxml)

百般思念 提交于 2019-12-10 21:31:48

问题


I have an XML structure like this:

mytree = """
<path>
    <to>
        <nodes>
            <info>1</info>
            <info>2</info>
            <info>3</info>
        </nodes>
    </to>
</path>
"""

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

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")

(but that doesn't work)


回答1:


You can use:

print info.xpath("/path/to/nodes/info/text()")


来源:https://stackoverflow.com/questions/9570632/just-returning-the-text-of-elements-in-xpath-python-lxml

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!