开源 Python 表格展示与排版库 Great Tables

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 字符串直接完成。

核心功能包括:

  1. 表格结构编排:支持标题、副标题、表头、表尾、行标签、分组表头、脚注和数据来源说明,可以组合出类似专业报告、学术论文的复杂表格。
  2. 数据格式化:提供货币、百分比、日期、数字、时长等格式化方法,支持紧凑数字表示、缺失值替换及自定义文本转换。
  3. 样式定制:可以设置单元格颜色、字体、对齐方式、边框、行间距和条件格式,还能通过数据颜色映射及迷你图增强数据表达效果。
  4. 多种输出格式:默认生成 HTML 表格,也支持导出图片、PDF 和 LaTeX 等格式,适用于 Jupyter Notebook、Quarto 文档及报告生成流程。
  5. 链式 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 内容编码到一个 Favicon 图标中

2026-06-27

我曾经有过一个实验,将文件编码存储到一个图片中。
没有想到还有人想到将网站内容存入一个 Favicon,然后通过 JS 解析出来,有意思。
虽然想不到什么实际意义,但是是一次有趣的探索实验。

Tim Wehrle 的文章《I Stored a Website in a Favicon》是这样说的:
PS:代码放在 GitHub 上。

  1. 编码过程:将 HTML 文本转为 UTF-8 字节数组 → 前置 4 字节记录载荷长度(便于截断尾部无用像素)→ 依次写入 PNG 像素的 R/G/B 通道(每像素存 3 字节),生成的图像看似随机噪点。

    <style>
        body {
            font-family: system-ui;
            max-width: 40rem;
            margin: 2rem auto;
        }
    </style>
    <h1>Website in a Favicon</h1>
    <p>Everything you're reading right now was decoded from favicon pixels.</p>
    

    HTML 载荷:208 字节 + 4 字节长度头 = 212 字节
    Favicon 部分:选择 9×9 正方形,81 像素,可以容纳 239 字节数据,Cover 上面的 HTML 负载(利用率约 87%)

  2. 解码过程:浏览器加载 favicon → 用 Canvas API 绘制并读取像素 RGB 值 → 还原字节数组 → 读取前 4 字节获知长度 → 提取载荷 → UTF-8 解码得到原 HTML → 替换页面内容渲染。

  3. 关键限制:favicon 只存内容,仍需一小段外部 JavaScript(bootstrap loader)来解码,无 JS 时它只是一张普通 PNG。

网页对电话号码的处理

2026-06-23

页面上加链接可以点击触发拨号 <a href="tel:+8613800138000">138****8000</a>,这个各浏览器都支持。

不同的是,iOS Safari 自动识别电话号码并注入拨号连接,而 Android Chrome 则没有这个行为。

在 iOS Safari 会自动扫描页面中的数字串(比如订单号、序列号、IP 地址),只要格式“看起来像电话”,就会偷偷把它们转换成可点击的拨号链接:

<a href="tel:1234567890">1234567890</a>

这会导致样式错乱,甚至误触拨号。

解决方案:

  • 全局关闭自动识别:

    <meta name="format-detection" content="telephone=no" />
    

    注意:这是 Apple 私有的规范,并非 W3C 标准。

  • 真正需要拨号的地方,手动声明:

    <a href="tel:+8613800138000">138****8000</a>
    

html2text:HTML 中提取文本

2026-02-11

一、需求说明

开发一个 Python HTML 文本提取工具,将 HTML 转换为纯文本,同时尽可能保留原始内容结构。

  1. 标签剥离:移除所有 HTML 标签,删除 HTML 注释及 script、style 等非正文元素及其内容。
  2. 结构保留:对 <br>、<div>、<p>、标题、列表等块级元素添加换行,避免文本粘连。
  3. 空白规范化:连续多个换行符合并为一个,清理普通文本行首、行尾的空格,去除文档首尾空白。
  4. 代码保护:保留 <pre>、<code> 内的代码内容及其缩进,不执行普通文本的行首、行尾空白清理。
  5. 实体解码:将 &amp;、&lt; 等 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> 内的空行也必须原样保留,需要进一步调整为分段规范化:普通文本单独清理,代码块整体跳过清理。

HTML 总结

2021-08-21

HTML5 的一个重要变化是彻底放弃 XML 化路线,也就是所谓的 “no logger based on SGML”,事实上 HTML5 就是因为浏览器厂商和 W3C 之间存在是否应该 XML 化这个分歧才诞生出来的。最终厂商联盟 WHATWG 获胜,取得了标准制定方面的绝对话语权(W3C 设计的 XHTML2 胎死腹中),其他的功能上的大跨度变化(除了本身的功能增加之外,对外设备连通性,性能)都只能算是副产品。

我们常说的 H5 实际上是 HTML5 + CSS3, JS 一般好像没有要求,应该还是默认 ES5, 不过现在 ES6 目前也已经在主流浏览器上得到了很好的支持。

黄色:废弃
绿色:新增
红色:非标准

标签

基础框架

  1. <!DOCTYPE>
  2. <!-- -->
  3. html
  4. head
  5. body
  6. title
  7. meta
  8. base
  9. basefont
  10. style
  11. link

文档结构

  1. p
  2. h1 ... h6
  3. ul, ol, li
  4. dl, dt, dd
  5. dir 使用 ul 替代
  6. span
  7. div
  8. table, tr, td, th, thead, tbody, tfoot, col, colgroup, caption
  9. a

样式/排版

  1. abbr, acronym 简写
  2. bdo 文字书写方向
  3. b, strong
  4. big, small
  5. center
  6. font
  7. i 斜体
  8. s, stike 中划线
  9. u 下划线
  10. del, ins 删除、插入,默认就是加上中划线和下划线
  11. em 强调
  12. dfn 术语
  13. q, blockquote, cite 引用
  14. address
  15. var 变量
  16. samp 样本
  17. kbd
  18. br
  19. hr
  20. sub, sup
  21. ruby, rt, rp
  22. pre, code

图片/视频/音频

  1. img
  2. map
  3. area
  4. canvas
  5. figcaption
  6. figure
  7. piture
  8. svg
  9. audio
  10. video
  11. source
  12. track

表单

  1. form
  2. input
  3. select
  4. textarea
  5. button
  6. option, optgroup
  7. label
  8. legend
  9. datalist 配合 input 使用
  10. output

Frame

  1. frame
  2. frameset
  3. noframes
  4. iframe

程序

  1. script
  2. noscript
  3. embed 可能是 v4 没有纳入标准
  4. object
  5. param
  6. applet

语义标签

  1. main
  2. header
  3. footer
  4. nav
  5. article
  6. aside
  7. section
  8. details
  9. dialog
  10. menu
  11. menuitem 火狐
  12. summary

Web Components

Custom Elements
H5 特性。

新的 API

  1. SVG
  2. Canvas
  3. 音频/视频
  4. WebRTC
  5. 本地存储
  6. WebStorage: LocalStorage + SessionStorage
  7. IndexedDB
  8. WebSQL
    PS: WebSQL 相关规范已经冻结,所以现在不属于 HTML5 标准,只有 Safari 和 Chrome 系浏览器支持。
    火狐全力支持 IndexedDB,认为一项标准不应该依赖一个具体的实现(SQLite),而且对于在网页端执行 SQL 非常不看好。
  9. WebAssembly
    这同样不属于 HTML5 的范畴,不过也是一项重要的标准,可能对 Web 开发产生很大的影响。
  10. WebSockets
  11. Server-Sent Event
  12. 2D/3D (WebGL)
  13. XMLHttpRequest Level 2

参考资料与拓展阅读