Get the inner HTML of a element in lxml
from lxml import etreeprint(etree.tostring(root, pretty_print=True))
you may see more examples here: http://lxml.de/tutorial.html
I believe you want to use the tostring()
method:
from lxml import etreetree = etree.fromstring('<html><head><title>foo</title></head><body><div class="name"><p>foo</p></div><div class="name"><ul><li>bar</li></ul></div></body></html>')for elem in tree.xpath("//div[@class='name']"): # pretty_print ensures that it is nicely formatted. print etree.tostring(elem, pretty_print=True)
Simple function to get innerHTML or innerXML
.
Try it out directly https://pyfiddle.io/fiddle/631aa049-2785-4c58-bf82-eff4e2f8bedb/
.
function
def innerXML(elem): elemName = elem.xpath('name(/*)') resultStr = '' for e in elem.xpath('/'+ elemName + '/node()'): if(isinstance(e, str) ): resultStr = resultStr + '' else: resultStr = resultStr + etree.tostring(e, encoding='unicode') return resultStr
invocation
XMLElem = etree.fromstring("<div>I am<name>Jhon <last.name> Corner</last.name></name>.I work as <job>software engineer</job><end meta='bio' />.</div>")print(innerXML(XMLElem))
.
Logic Behind
- get the outermost element name first,
- Then get all the child nodes
- Convert all the child nodes to string using
tostring
- Concatinate Them