Just returning the text of elements in xpath (python / lxml)
19,526
You can use:
print info.xpath("/path/to/nodes/info/text()")
Related videos on Youtube
Author by
LittleBobbyTables
Updated on June 04, 2022Comments
-
LittleBobbyTables almost 2 years
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)