python - 如何递归地将 HTML 映射到 Python 字典?
问题描述
我看过一些专门关于 HTML 表的文章,但我想知道如何将整个 HTML 文件映射到 Python 字典(稍后转换为 JSON)。我正在映射的 HTML 主要是来自 Confluence API 调用的文本页面(可能带有一些图像)。
示例输入:
<h1>This is a header</h1>
<p>Here is a paragraph with <b>some bold text!</b>Some more words here.</p>
<div>
<h2>Here is a nested header</h2>
</div>
示例输出:
{
"h1": "This is a header",
"p":{
"text_content0": "Here is a paragraph with "
"b": "some bold text!",
"text_content1": "Some more words here."
},
"div":{
"h2": "Here is a nested header"
}
}
我知道这必须是递归的。我一直在研究作为 Python 一部分的 HTML Parser,并且我一直在尝试将递归功能应用到它们提供的示例中:
from html.parser import HTMLParser
class MyHTMLParser(HTMLParser):
def handle_starttag(self, tag, attrs):
print("Encountered a start tag:", tag)
def handle_endtag(self, tag):
print("Encountered an end tag :", tag)
def handle_data(self, data):
print("Encountered some data :", data)
parser = MyHTMLParser()
parser.feed('<html><head><title>Test</title></head>'
'<body><h1>Parse me!</h1></body></html>')
有谁知道修改这个示例(或从头开始)以创建一个完全代表 HTML 文件的嵌套字典的方法?
解决方案
推荐阅读
- python-3.x - 有没有办法在使用 PIL 加载图像时忽略 EXIF 方向数据?
- c++ - 如何将我从 linux 共享库生成的资源句柄限制为一个客户端
- reactjs - React-Codemirror2 未加载自动完成
- sql - SQL:在不添加 GROUP BY 的情况下获取附加列
- android - Osmdroid 不显示地图
- flutter - 按下后退按钮并且用户从新材料页面路径返回到父级后,如何清空父级中的列表
- r - 闪亮的应用程序在我的数据集中找不到属性
- firebase - 错误:projects:list 不是 Firebase 命令
- android - 缩放图像在手机上无法正常工作
- java - 使用 KeyListener 加载和更新 BufferedImage 组件