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

无法安装第三方包时,如何在Python3中构建可调用HTML属性的对象?

在Python3中模拟Python2的html.HTML类功能

由于Python3标准库的html模块移除了HTML类,且无法安装第三方包,你可以自己实现一个轻量级的类来模拟原有的功能,支持通过obj.head、obj.div、obj.p这类方式创建HTML元素。

实现代码

import html

class HTMLNode:
    def __init__(self, tag):
        self.tag = tag
        self.children = []
        self.attributes = {}

    def __call__(self, **kwargs):
        # 支持设置元素属性,比如 div(class_='container')
        self.attributes.update(kwargs)
        return self

    def __getattr__(self, name):
        # 动态创建子元素,比如 obj.div.p 会创建div下的p元素
        if name == 'text':
            # 特殊处理文本内容,自动转义特殊字符
            def add_text(content):
                self.children.append(html.escape(str(content)))
            return add_text
        child = HTMLNode(name)
        self.children.append(child)
        return child

    def render(self, indent=0):
        # 生成格式化的HTML字符串
        indent_str = '  ' * indent
        # 转义属性值,同时处理class_转成class的特殊情况
        attrs = ''.join([f' {k.rstrip("_")}="{html.escape(str(v))}"' for k, v in self.attributes.items()])
        
        if not self.children:
            return f'{indent_str}<{self.tag}{attrs} />'
        
        start_tag = f'{indent_str}<{self.tag}{attrs}>'
        child_content = []
        for child in self.children:
            if isinstance(child, str):
                child_content.append(f'{indent_str}  {child}')
            else:
                child_content.append(child.render(indent + 1))
        end_tag = f'{indent_str}</{self.tag}>'
        return '\n'.join([start_tag] + child_content + [end_tag])

class HTML:
    def __init__(self, root_tag='html'):
        self.root = HTMLNode(root_tag)

    def __getattr__(self, name):
        return getattr(self.root, name)

    def render(self):
        return self.root.render()

使用示例

# 与Python2类似的用法
obj = HTML('html')

# 创建head部分
obj.head.title.text('My Custom Page')
obj.head.meta(charset='UTF-8')
obj.head.link(rel='stylesheet', href='style.css')

# 创建body部分
obj.body.h1(id='main-title').text('Hello, Python3!')
obj.body.div(class_='content').p.text('This is a paragraph built with our custom HTML class.')
obj.body.div(class_='content').ul.li.text('First list item')
obj.body.div(class_='content').ul.li.text('Second list item')

# 输出最终格式化的HTML
print(obj.render())

功能说明

  • 支持通过obj.tag的方式动态创建任意HTML元素,比如obj.footer会生成<footer>标签
  • 支持通过tag(**kwargs)设置元素属性,用class_代替class以规避Python关键字冲突
  • 内置text()方法添加文本内容,自动转义<、>等特殊字符避免XSS风险
  • render()方法生成结构清晰、可直接使用的格式化HTML字符串
  • 完全基于Python3标准库实现,无需安装任何第三方依赖

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.19 09:30:26