获取lxm中元素的内部HTML

2024-04-19 10:05:30 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图用Python中的lxml和xpath获取子节点的HTML内容。如下面的代码所示,我想找到每个产品节点的html内容。它有没有像product.html这样的方法?

productGrids = tree.xpath("//div[@class='name']/parent::*")
for product in productGrids:
    print #html content of product

Tags: 方法代码divtree内容节点产品html
2条回答

您可以使用product.text_content()

我相信您想使用tostring()方法:

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)

相关问题 更多 >