Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get inner text from lxml

Tags:

python

lxml

lxml.html.fromstring insists on wrapping up everything in a tag (p default). From this tag tree,

<p>this is <b>the</b> good stuff<p>

I want to extract the string:

this is <b>the</b> good stuff

How do I do this?

like image 987
Jesvin Jose Avatar asked Jun 11 '15 06:06

Jesvin Jose


Video Answer


1 Answers

That's often referred to as "inner xml" rather than "inner text". This is one possible way to get inner xml of an element :

import lxml.etree as etree
import lxml.html

html = "<p>this is <b>the</b> good stuff<p>"
tree = lxml.html.fromstring(html)
node = tree.xpath("//p")[0]

result = node.text + ''.join(etree.tostring(e) for e in node)
print(result)

output :

this is <b>the</b> good stuff
like image 176
har07 Avatar answered Oct 31 '22 04:10

har07