Get the inner HTML of a element in lxml
41,763
Solution 1
from lxml import etree
print(etree.tostring(root, pretty_print=True))
you may see more examples here: http://lxml.de/tutorial.html
Solution 2
I believe you want to use the tostring()
method:
from lxml import etree
tree = 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)
Author by
Sudip Kafle
Python / Django developer Twitter: @kaflesudip Linkedin: @kaflesudip
Updated on October 10, 2021Comments
-
Sudip Kafle over 2 years
I am trying to get the HTML content of child node with lxml and xpath in Python. As shown in code below, I want to find the html content of the each of product nodes. Does it have any methods like product.html?
productGrids = tree.xpath("//div[@class='name']/parent::*") for product in productGrids: print #html content of product