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

Python的dominate模块处理换行符转HTML<br>标签问题求助

问题原因

dominate默认会对所有传入的文本内容做HTML实体转义,避免XSS注入风险,所以你手动替换的<br>会被转成&lt;br&gt;无法生效,而直接传入的\n在HTML中本身不会被识别为换行,只会被当成普通空白字符。

解决方法

方法1:使用raw()方法跳过转义(适合信任文本来源的场景)

dominate内置了dominate.util.raw方法,传入的内容不会被转义,会直接渲染为原始HTML内容。
示例代码:

import dominate
from dominate.tags import *
from dominate.util import raw

text = "Hello\nworld!"
# 先替换换行符为<br>标签
processed_text = text.replace("\n", "<br>")
doc = dominate.document(title='Dominate your HTML')
with doc:
   h1(raw(processed_text))

with open("dominate22.html", 'w') as file:
   file.write(doc.render())

方法2:拆分文本手动插入br标签(更安全,适合不可信文本来源)

如果文本内容来自用户输入等不可信场景,不建议直接使用raw()避免XSS风险,可以把文本按\n拆分后,循环插入文本和br标签:
示例代码:

import dominate
from dominate.tags import *

text = "Hello\nworld!"
doc = dominate.document(title='Dominate your HTML')
with doc:
    with h1():
        lines = text.split('\n')
        for index, line in enumerate(lines):
            # 非首行前插入换行标签
            if index > 0:
                br()
            # 插入文本内容,会自动转义特殊字符
            += line

with open("dominate22.html", 'w') as file:
   file.write(doc.render())

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.28 13:27:00