You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用Python将HTML转换为无冗余标签的层级式JSON结构?

HTML转JSON:去除冗余标签并生成指定层级结构

我尝试用以下Python代码将本地HTML文件转换为JSON:

import html_to_json
import json
def htmltojson():
    with open("C:\Extraction\Sample.html", "r") as html_file:
        html = html_file.read()
        output_json = html_to_json.convert(html,capture_element_attributes=False,capture_element_values=True)
    with open('Final.json', 'w') as outfile:
        json.dump(output_json, outfile,indent=4)
        print(output_json)

但转换得到的JSON包含span等HTML标签冗余内容,我期望得到仅含key、value及child的层级式JSON结构,示例格式如下:

[
{
"key": "1",
"value": "",
"child":[]
},
{
"key": "2",
"value": "",
"child":[{
"key": "2.1",
"value": "",
"child":[]
},
{
"key": "2.2",
"value": "",
"child":[]
}]
},
{
"key": "3",
"value": "",
"child":[{
"key": "2.1",
"value": "",
"child":[{
"key": "2.1.1",
"value": "",
"child":[]
}]
}]
},
]

内容的提问来源于stack exchange,提问作者amnpawar

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.18 11:26:11