Sud*_*fle 24 python xpath lxml
我试图在Python中使用lxml和xpath获取子节点的HTML内容.如下面的代码所示,我想找到每个产品节点的html内容.它有像product.html这样的方法吗?
productGrids = tree.xpath("//div[@class='name']/parent::*")
for product in productGrids:
print #html content of product
Run Code Online (Sandbox Code Playgroud)
Wal*_*ung 34
from lxml import etree
print(etree.tostring(root, pretty_print=True))
Run Code Online (Sandbox Code Playgroud)
您可以在此处看到更多示例:http://lxml.de/tutorial.html
vez*_*ult 13
我相信你想使用这个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)
Run Code Online (Sandbox Code Playgroud)