我如何使用lxml和python遍历 of a html document along with its children

问题描述 投票:0回答:2

我想带一个html文档,并与其子项遍历文档的<body>部分。我看到很多例子通过xpath或标签名称获得子树,但这似乎没有给孩子们。

import lxml
from lxml import html, etree  

html3 = "<html><head><title>test<body><h1>page title</h3><p>some text</p>"
root = lxml.html.fromstring(html3)
tree = etree.ElementTree(root)
for el in root.iter():
    # do something
    print(el.text, tree.getpath(el))

这将输出

None /html
None /html/head
test /html/head/title
None /html/body
page title /html/body/h1
some text /html/body/p

我只想

page title /html/body/h1
some text /html/body/p

任何帮助感激不尽。

python lxml
2个回答
1
投票

我有类似的困难,然后我想每个etree节点有一个迭代器,如果它的父级使用你可以遍历

例如,root这里将使用你可以迭代身体的每个元素的身体

from lxml import etree
parser = etree.HTMLParser()
tree   = etree.parse('yourdocument.html', parser)

root = tree.xpath('/html/body/')[0]
for i in root.getiterator():
    print(i.tag,i.text)

0
投票

看来你的HTML代码格式无效,我只是用beautifuSoup写了一个小程序,也许你可以用来修改你的目的:

from bs4 import BeautifulSoup
html3 = "<html><head><title>test</title></head><body><h1>page title</h1><p>some text</p><body></html>"
soup = BeautifulSoup(html3, "html5lib")
body = soup.find('body')

for item in body.findChildren():
    print(item)

产量

<h1>page title</h1>
<p>some text</p>
© www.soinside.com 2019 - 2024. All rights reserved.