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

如何使用Beautiful Soup修改HTML标签的style属性值

使用Beautiful Soup修改HTML标签的style属性值

你可以通过两种方式修改style属性里的具体值:直接字符串替换(简单场景适用),或者解析style为字典后修改(更稳健)。

方法一:直接字符串替换

如果你的style属性格式固定,直接用字符串替换就能快速修改:

# 修改<td>的background-color
tag['style'] = tag['style'].replace('background-color: #e5e5e5;', 'background-color: #762157;')

# 修改<p>的line-height
tag.p['style'] = tag.p['style'].replace('line-height: 16px;', 'line-height: 17px;')

方法二:解析style为字典修改(更稳健)

如果style属性的格式可能有变化(比如空格、属性顺序不同),可以先把style字符串解析成字典,修改对应值后再重新生成style字符串:

def parse_style(style_str):
    style_dict = {}
    # 拆分style的每个属性
    for item in style_str.split(';'):
        item = item.strip()
        if not item:
            continue
        # 拆分属性名和属性值
        key, value = item.split(':', 1)
        style_dict[key.strip()] = value.strip()
    return style_dict

def build_style(style_dict):
    # 把字典重新拼接成style字符串
    return '; '.join([f"{k}: {v}" for k, v in style_dict.items()]) + ';'

# 修改<td>的background-color
td_style = parse_style(tag['style'])
td_style['background-color'] = '#762157'
tag['style'] = build_style(td_style)

# 修改<p>的line-height
p_style = parse_style(tag.p['style'])
p_style['line-height'] = '17px'
tag.p['style'] = build_style(p_style)

执行完上述代码后,打印tag就能得到你想要的结果:

<td style="background-color: #762157;">
  <p style="margin: 0; font-size: 12px; line-height: 17px; font-family: Arial, sans-serif; text-align: center;">10</p>
</td>

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.19 16:00:26