python - BeautifulSoup自动关闭未关闭的html标签

标签 python html parsing beautifulsoup

我对 BeautifukSoup 有疑问。每当我解析 HTML 输入时,它都会关闭未关闭的 HTML 标签(例如 <input> 或未错误关闭的标签)。

例如:

from bs4 import BeautifulSoup

tags = BeautifulSoup('<span id="100" class="test">', "html.parser")
print(str(tags))

打印:

<span id="100" class="test"></span>

我的主要目标是在解析 HTML 输入后保留其原始形状。

我发现使用 "XML" parser 是可能的而不是“html.parser”,但我希望解决“html.parser”的问题。

最佳答案

您可以poke through bs4 internals并修改 html.parser 处理 HTML 的方式(这适用于我的版本 bs4==4.12.2):

from bs4 import BeautifulSoup
from bs4.builder import builder_registry
from bs4.formatter import HTMLFormatter


class UnsortedAttributes(HTMLFormatter):
    def __init__(self):
        super().__init__(
            void_element_close_prefix=""
        )  # <-- use void_element_close_prefix="" here

    def attributes(self, tag):
        yield from tag.attrs.items()


html_text = """\
<closed_tag>
    <my_tag id="xxx">
    <my_other_tag id="zzz">
</closed_tag>"""

builder_registry.lookup("html.parser").empty_element_tags = {"my_tag", "my_other_tag"}

soup = BeautifulSoup(html_text, "html.parser")
print(soup.encode(formatter=UnsortedAttributes()).decode())

打印:

<closed_tag>
<my_tag id="xxx">
<my_other_tag id="zzz">
</closed_tag>

关于python - BeautifulSoup自动关闭未关闭的html标签,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/76807671/

相关文章:

javascript - 无法将 div 定位在我想要的位置

python - 使用 lxml 将多个元素添加到 xml

html - 如何使 HTML 工具提示在溢出 :hidden parent? 中完全可见

python - 从多行修剪空白

html - 移动页面全 Angular - 带图标的居中文本

c++ - 当语言环境需要 "3.14"时,如何使用 scanf 解析 "3,14"之类的数字

php - PHP解析/语法错误;以及如何解决它们

r - 如何向 ggplot geom_text 标签添加百分比和分数?

Python:将两个列表压缩在一起而不截断

python - 简单的 python 列表与字典