如何用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
相关产品推荐
相关产品推荐

