【发布时间】:2019-09-10 21:43:48
【问题描述】:
我正在尝试在 Python 中使用 lxml 解析 HTML 页面。
在 HTML 中有这样的结构:
<html>
<h5>Title</h5>
<p>Some text <b>with</b> <i>other tags</i>.</p>
<p>More text.</p>
<p>More text[2].</p>
<h5>Title[2]</h5>
<p>Description.</p>
<h5>Title[3]</h5>
<p>Description[1].</p>
<p>Description[2].</p>
***
and so on...
***
</html>
我需要将此 HTML 解析为以下 JSON:
[
{
"title": "Title",
"text": "Some text with other tags.\nMore text.\nMore text[2].",
},
{
"title": "Title[2]",
"text": "Description.",
},
{
"title": "Title[3]",
"text": "Description[1].\nDescription[2]",
}
]
我可以读取所有带有标题的 h5 标签并使用以下代码将它们写入 JSON:
array = []
for title in tree.xpath('//h5/text()'):
data = {
"title" : title,
"text" : ""
}
array.append(data)
with io.open('data.json', 'w', encoding='utf8') as outfile:
str_ = json.dumps(array,
indent=4, sort_keys=True,
separators=(',', ' : '), ensure_ascii=False)
outfile.write(to_unicode(str_))
问题是,我不知道如何阅读<h5>标题之间的所有这些段落内容并将它们放入text JSON字段中。
【问题讨论】:
-
我唯一能想到的就是逐个标签解析所有内容并构建它的 JSON...
标签: python html-parsing lxml