Python HTML
2026-10-29
Great Tables 是由 Posit 团队维护的开源 Python 表格展示与排版库,项目地址:posit-dev/great-tables。它的核心定位是将 Pandas、Polars 等数据框中的结构化数据,转换为适合报告、数据分析文档和网页展示的高质量格式化表格,而不是提供数据处理或交互式数据探索能力。
Great Tables 的核心输出是 HTML 表格,主要通过 HTML + CSS 实现排版和样式,而不是提供一套独立的前端 UI 组件。
- 渲染层:生成 HTML 表格结构,并使用 CSS 控制字体、颜色、边框、间距、条件格式等视觉效果。
- 交互层:它不是 DataTables、AG Grid 这类面向 Web 应用的交互式表格组件,核心目标是静态数据展示和报告排版,而不是提供排序、筛选、编辑等完整交互能力。
另外,它也支持将 CSS 内联到 HTML 元素中,方便嵌入邮件模板等对样式支持有限的环境;还可以导出 PNG、JPEG、WebP 和 PDF。需要注意,图片和 PDF 导出涉及浏览器渲染,并非仅靠 HTML 字符串直接完成。
核心功能包括:
- 表格结构编排:支持标题、副标题、表头、表尾、行标签、分组表头、脚注和数据来源说明,可以组合出类似专业报告、学术论文的复杂表格。
- 数据格式化:提供货币、百分比、日期、数字、时长等格式化方法,支持紧凑数字表示、缺失值替换及自定义文本转换。
- 样式定制:可以设置单元格颜色、字体、对齐方式、边框、行间距和条件格式,还能通过数据颜色映射及迷你图增强数据表达效果。
- 多种输出格式:默认生成 HTML 表格,也支持导出图片、PDF 和 LaTeX 等格式,适用于 Jupyter Notebook、Quarto 文档及报告生成流程。
- 链式 API:以
GT() 为入口,通过连续调用 tab_header()、fmt_currency()、cols_hide() 等方法逐步构建表格,代码可读性较好。
典型使用场景包括经营分析报告、财务报表、统计数据发布、研究论文、数据分析 Notebook,以及自动化生成的 HTML 报告。
安装方式:
pip install great_tables
简单示例:
from great_tables import GT
table = (
GT(df)
.tab_header(title="销售业绩报告")
.fmt_currency(columns=["revenue"])
.fmt_number(columns=["orders"], compact=True)
)
其中 df 是已有的 Pandas 或 Polars 数据框。
Great Tables 可以理解为 Python 生态中的专业表格排版引擎,优势在于声明式 API、丰富的格式化能力和高质量输出。如果需要将统计结果直接呈现为可发布的报告表格,它比手动拼接 HTML 更合适;如果需要前端实时交互、排序筛选或复杂的数据管理界面,则应考虑专门的 Web 表格组件。该项目采用 MIT 开源许可证,适合商业项目集成。
项目提供了一个 Skill 供安装:https://posit-dev.github.io/great-tables/skills.html
name: great-tables
description: >
Easily generate information-rich, publication-quality tables from Python. Use when writing Python code that uses the great_tables package.
license: MIT
compatibility: Requires Python >=3.10.
HTML
2026-02-11
一、需求说明
开发一个 Python HTML 文本提取工具,将 HTML 转换为纯文本,同时尽可能保留原始内容结构。
- 标签剥离:移除所有 HTML 标签,删除 HTML 注释及
script、style 等非正文元素及其内容。
- 结构保留:对
<br>、<div>、<p>、标题、列表等块级元素添加换行,避免文本粘连。
- 空白规范化:连续多个换行符合并为一个,清理普通文本行首、行尾的空格,去除文档首尾空白。
- 代码保护:保留
<pre>、<code> 内的代码内容及其缩进,不执行普通文本的行首、行尾空白清理。
- 实体解码:将
&、< 等 HTML 字符实体还原为对应字符。
实现时使用 HTML 解析器而非正则表达式剥离标签,以更可靠地处理嵌套元素和不规范的 HTML。代码块内部的空白保护优先于普通文本规范化。
二、Python 实现
使用标准库 html.parser.HTMLParser,无需安装第三方依赖。代码通过占位符保护 <code> 和 <pre> 内容,避免普通文本清理规则破坏代码缩进。
#!/usr/bin/env python3
"""Extract plain text from HTML while preserving code whitespace."""
import argparse
import re
import sys
from html.parser import HTMLParser
BLOCK_TAGS = {
"address", "article", "aside", "blockquote", "br",
"dd", "div", "dl", "dt", "fieldset", "figcaption",
"figure", "footer", "form", "h1", "h2", "h3",
"h4", "h5", "h6", "header", "hr", "li", "main",
"nav", "ol", "p", "section", "table", "tbody",
"td", "tfoot", "th", "thead", "tr", "ul",
}
# These elements and all their contents are discarded.
IGNORE_TAGS = {
"head", "script", "style", "noscript",
"template", "iframe", "object",
}
VOID_TAGS = {
"area", "base", "br", "col", "embed", "hr", "img",
"input", "link", "meta", "param", "source", "track", "wbr",
}
class TextExtractor(HTMLParser):
def __init__(self):
super().__init__(convert_charrefs=True)
self.parts = []
self.stack = []
self.ignore_depth = 0
self.code_depth = 0
self.code_blocks = []
def handle_starttag(self, tag, attrs):
if self.ignore_depth:
if tag not in VOID_TAGS:
self.stack.append(tag)
self.ignore_depth += 1
return
if tag in IGNORE_TAGS:
self.ignore_depth = 1
self.stack.append(tag)
return
if tag in BLOCK_TAGS:
self.parts.append("\n")
if tag in {"code", "pre"}:
self.code_depth += 1
if tag not in VOID_TAGS:
self.stack.append(tag)
def handle_startendtag(self, tag, attrs):
self.handle_starttag(tag, attrs)
if tag not in VOID_TAGS:
self.handle_endtag(tag)
def handle_endtag(self, tag):
if self.ignore_depth:
# HTML is usually properly nested; tolerate malformed input.
if tag in self.stack:
while self.stack:
current = self.stack.pop()
if current in IGNORE_TAGS:
self.ignore_depth = 0
break
return
if tag not in self.stack:
return
# Recover from imperfectly nested HTML.
while self.stack:
current = self.stack.pop()
if current in {"code", "pre"}:
self.code_depth = max(0, self.code_depth - 1)
if current in BLOCK_TAGS:
self.parts.append("\n")
if current == tag:
break
def handle_data(self, data):
if self.ignore_depth or not data:
return
if self.code_depth:
self.code_blocks.append(data)
self.parts.append(("CODE", len(self.code_blocks) - 1))
else:
self.parts.append(data)
def get_text(self):
# Replace protected code with unique placeholders.
output = []
for part in self.parts:
if isinstance(part, tuple):
output.append(f"\x00CODE{part[1]}\x00")
else:
output.append(part)
text = "".join(output)
# Collapse consecutive newlines and surrounding whitespace.
text = re.sub(r"[^\S\n]*\n(?:[^\S\n]*\n)+", "\n", text)
text = re.sub(r"[ \t]*\n[ \t]*", "\n", text)
text = text.strip()
# Trim ordinary lines without changing protected code.
lines = text.split("\n")
lines = [line.strip() for line in lines]
text = "\n".join(lines)
# Restore original code contents.
for i, code in enumerate(self.code_blocks):
text = text.replace(f"\x00CODE{i}\x00", code)
return text
def html_to_text(html: str) -> str:
parser = TextExtractor()
parser.feed(html)
parser.close()
return parser.get_text()
def main():
arg_parser = argparse.ArgumentParser(
description="Extract plain text from HTML."
)
arg_parser.add_argument(
"file", nargs="?", help="HTML file; reads stdin if omitted"
)
args = arg_parser.parse_args()
if args.file:
with open(args.file, encoding="utf-8") as f:
html = f.read()
else:
html = sys.stdin.read()
print(html_to_text(html))
if __name__ == "__main__":
main()
三、使用方法
保存为 html2text.py,直接运行:
# 读取 HTML 文件
python html2text.py input.html
# 通过管道输入
cat input.html | python html2text.py
# 将结果保存到文件
python html2text.py input.html > output.txt
四、注意事项
当前实现适合常规 HTML 文本提取,但有两个值得注意的边界:
- 代码块保护:占位符方案能保护代码内部空白,但代码块内部包含多个 HTML 文本节点时,会将这些节点分别保护;如果需要严格保留整个
<pre> 的原始内容,建议将代码块作为整体收集后再恢复。
- HTML 容错:
HTMLParser 不会像浏览器那样完整修复所有错误嵌套结构。对于来源复杂的网页,可考虑使用 BeautifulSoup 配合 html5lib,代价是增加第三方依赖。
另外,当前实现对连续换行的规范化是全局进行的。如果要求 <pre> 内的空行也必须原样保留,需要进一步调整为分段规范化:普通文本单独清理,代码块整体跳过清理。