首页 > 解决方案 > 如何递归地将 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 文件的嵌套字典的方法?

标签: pythonhtml

解决方案


推荐阅读