You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何阻止BeautifulSoup解析HTML时打乱标签属性顺序?

解决BeautifulSoup解析HTML时属性顺序被修改的问题

默认情况下,BeautifulSoup使用Python标准库的html.parser解析器时,会对标签属性进行重新排序(比如按字母顺序),这是因为该解析器内部以无序结构存储属性。如果需要保留原始HTML的属性顺序以支持字符级匹配,可以通过以下两种方式解决:

方法一:使用html5lib解析器

html5lib解析器会严格保留HTML原始的属性顺序和结构,只需先安装该库,再修改解析器参数即可:

  1. 安装依赖:
pip install html5lib
  1. 修改代码:
from bs4 import BeautifulSoup

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

执行后输出将与原始输入一致:

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

方法二:自定义属性存储顺序(进阶)

如果不想额外安装依赖,可以通过修改BeautifulSoup的属性存储方式,使用有序字典来保留属性顺序。需要自定义一个继承自BeautifulSoup的类,重写__init__方法:

from bs4 import BeautifulSoup
from collections import OrderedDict

class OrderedBeautifulSoup(BeautifulSoup):
    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        # 让标签使用OrderedDict存储属性
        self.builder.defaults['attrs'] = OrderedDict

# 使用自定义类解析
tags = OrderedBeautifulSoup('<span id="100" class="test"></span>', "html.parser")
print(str(tags))

注意:这种方法仅对Python 3.7以下版本(字典无序)有效,Python 3.7+字典本身已支持插入顺序,但html.parser仍可能会调整属性顺序,因此更推荐第一种方法。

内容的提问来源于stack exchange,提问作者Minions

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.14 11:40:01