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

如何让Python的PrettyTable正确渲染HTML格式的表格标题?

解决PrettyTable渲染HTML格式标题时的转义问题

PrettyTable默认会对HTML输出中的所有文本(包括标题)进行转义,导致传入的HTML标签被转换成实体字符无法正常解析。这里提供两种可行的解决方法:

方法一:手动反转义生成的HTML字符串

直接对生成的HTML内容进行处理,将标题部分的转义字符替换回原始HTML标签:

from prettytable import PrettyTable
import re

table = PrettyTable()
table.field_names = ["Name", "Email", "Phone"]
table.add_row(["John Smith", "john.smith@email.com", "XXX-XXX-XXXX"])

# 生成带转义标题的HTML
html_str = table.get_html_string(title='<a href="www.example.com">Table</a>')
# 反转义caption标签内的内容
fixed_html = re.sub(
    r'<caption>(&lt;.*?&gt;.*?&lt;/.*?&gt;)</caption>',
    lambda m: m.group(0).replace('&lt;', '<').replace('&gt;', '>').replace('&quot;', '"'),
    html_str
)

print(fixed_html)

方法二:自定义HTML格式化器(推荐)

通过继承HTMLFormatter重写标题格式化逻辑,让标题跳过转义步骤,这种方式更适合长期复用:

from prettytable import PrettyTable, HTMLFormatter

class HTMLTitleFormatter(HTMLFormatter):
    def format_title(self, title):
        # 不对标题做转义,直接返回原始HTML内容
        return f'<caption>{title}</caption>' if title else ''

# 创建表格并添加数据
table = PrettyTable()
table.field_names = ["Name", "Email", "Phone"]
table.add_row(["John Smith", "john.smith@email.com", "XXX-XXX-XXXX"])

# 使用自定义格式化器生成HTML
print(table.get_html_string(
    title='<a href="www.example.com">Table</a>',
    formatter=HTMLTitleFormatter()
))

两种方法都能得到正确的HTML输出,其中自定义格式化器的方式更符合代码设计原则,避免了字符串替换可能带来的意外问题。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.01 20:00:55