BeautifulSoup 洗牌 html 标签的属性

BeautifulSoup shuffles the attributes of html tags

提问人:Minions 提问时间:8/1/2023 更新时间:8/1/2023 访问量:30

问:

我对 BeautifukSoup 有疑问。每当我解析HTML输入时,它都会更改HTML标签的属性(例如.class,id)的顺序。

例如:

from bs4 import BeautifulSoup

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

指纹:

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

如您所见,和的顺序已更改。如何防止此类行为?classid

我不熟悉 Web 开发,但我知道属性的顺序并不重要。

我在这里的主要目标是在解析 HTML 输入后保留它的原始形状,因为我想遍历标签并将它们(在字符级别)与其他 HTML 文本进行匹配。

python html 解析 beautifulsoup

评论

0赞 Barmar 8/1/2023
当它解析它时,它不会保留顺序,因为它不相关。

答:

3赞 Andrej Kesely 8/1/2023 #1

正如您所说,HTML 中属性的顺序并不重要。但是,如果您真的想要未排序的属性,则可以执行以下操作:

from bs4 import BeautifulSoup
from bs4.formatter import HTMLFormatter


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


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

print(tags.encode(formatter=UnsortedAttributes()).decode())

指纹:

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

编辑:要不关闭void标签,您可以尝试:

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()


tags = BeautifulSoup(
    """<input id="NOT_CLOSED_TAG" type="Button">""",
    "html.parser",
)

print(tags.encode(formatter=UnsortedAttributes()).decode())

指纹:

<input id="NOT_CLOSED_TAG" type="Button">

评论

0赞 Minions 8/1/2023
我有一些类似的东西,那就是,如果一个标签没有关闭,beautifulsoup 会关闭它(例如 变成 )。有没有可能解决这个问题?<input><input/>
1赞 Andrej Kesely 8/1/2023
@Minions 这是一个更难的问题,因为每个解析器(、、)处理这个问题的方式有点不同。我已经编辑了我的答案,您可以尝试在格式化程序中放入构造函数。html.parserhtml5liblxmlvoid_element_close_prefix=""
0赞 Minions 8/1/2023
我真的很感谢你@Andrej的努力!它实际上有效,但仅适用于标签。如果我使用这样的东西,它不起作用。input<span id="100" class="test">
1赞 Andrej Kesely 8/1/2023
@Minions我只能指出如何处理特殊的 HTML 标签(毕竟,它是 HTML/XML 解析器):git.launchpad.net/beautifulsoup/tree/bs4/builder/......您可以子类化并使用 custom ,但这需要更多的工作......bs4TreeBuilderempty_element_tags