获取lxml中元素的内部HTML

问题描述 投票:21回答:5

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

productGrids = tree.xpath("//div[@class='name']/parent::*")
for product in productGrids:
    print #html content of product
python xpath lxml
5个回答
32
投票
from lxml import etree
print(etree.tostring(root, pretty_print=True))

你可能会在这里看到更多的例子:http://lxml.de/tutorial.html


12
投票

我相信你想使用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)

0
投票

你可以使用product.text_content()


-1
投票

另一种方法

x=doc.xpath("//div[@class='name']/parent::*")
print(map(etree.tostring,x))

-2
投票

在您想要的特定字段上右键单击(复制,复制xpath)后(在chrome的检查器中),您可能会得到以下内容:

//*[@id="specialID"]/div[12]/div[2]/h4/text()[1]

如果你想要每个“specialID”的文本元素

//*[@id="specialID"]/div/div[2]/h4/text()[1]

您可以选择另一个字段,它将交错结果

//*[@id="specialID"]/div/div[2]/h4/text()[1] | //*[@id="specialID"]/div/some/weird/path[95]

示例可以改进,但它说明了这一点:

//*[@id="mw-content-text"]/div/ul[1]/li[11]/text()

from lxml import html
import requests
page = requests.get('https://en.wikipedia.org/wiki/Web_scraping')
tree = html.fromstring(page.content)
data = tree.xpath('//*[@id="mw-content-text"]/div/ul[1]/li/a/text() | //*[@id="mw-content-text"]/div/ul[1]/li/text()[1]')
print(len(data))
for i in range(len(data)):
    print(data[i])
© www.soinside.com 2019 - 2024. All rights reserved.