# 文件名: html.pydef html_tag(tag_name):"""创建通用 HTML 标签函数"""def tag_func(*content, **attrs):# 处理属性attr_str = " ".join(f'{key}="{value}"' if value is not None else keyfor key, value in attrs.items())# 开始标签open_tag = f"<{tag_name} {attr_str}".strip() + ">"# 结束标签close_tag = f"</{tag_name}>"if not content:# 自闭合标签(例如 <img />)if tag_name in {"img", "input", "br", "hr", "meta", "link"}:return open_tag[:-1] + " />"else:return open_tag + close_tag# 处理内容部分,支持逗号分隔rendered_content = "".join(item() if callable(item) else str(item) for item in content)return f"{open_tag}{rendered_content}{close_tag}"return tag_func# 常见 HTML 标签函数
html = html_tag("html")
head = html_tag("head")
body = html_tag("body")
div = html_tag("div")
span = html_tag("span")
p = html_tag("p")
a = html_tag("a")
img = html_tag("img")
ul = html_tag("ul")
li = html_tag("li")
h1 = html_tag("h1")
h2 = html_tag("h2")
h3 = html_tag("h3")
br = html_tag("br")
style = html_tag("style")
script = html_tag("script")
link = html_tag("link")
meta = html_tag("meta")
title = html_tag("title")# 工具函数:生成完整的 HTML 页面
def render_html_page(title_text, body_content, styles=None, scripts=None, metas=None):"""生成完整的 HTML 页面。- title_text: 页面标题- body_content: 页面主体内容(可以嵌套组合)- styles: 内联 CSS 或外部 CSS 链接列表- scripts: 内联 JS 或外部 JS 链接列表- metas: 额外的 meta 标签内容"""# 处理 <meta> 标签meta_tags = "".join(meta(**meta_attr) for meta_attr in (metas or []))# 处理 <style> 标签和 <link> 标签style_tags = "".join(style(css) if isinstance(css, str) else link(rel="stylesheet", href=css)for css in (styles or []))# 处理 <script> 标签script_tags = "".join(script(js) if isinstance(js, str) else script(src=js)for js in (scripts or []))# 生成完整 HTMLreturn html(head(meta(charset="UTF-8"),title(title_text),meta_tags,style_tags),body(body_content, script_tags))# 测试示例
if __name__ == "__main__":# 页面内容page_content = div(h1("Welcome to My Page", class_="main-title"),p("This is an example paragraph.", class_="description"),a("Click me", href="https://example.com", target="_blank"),img(src="image.png", alt="Sample Image"),class_="content-wrapper")# 样式和脚本styles = [""".main-title {color: blue;font-size: 24px;}.description {color: gray;}""", # 内联 CSS"styles.css" # 外部 CSS]scripts = ["""console.log('Hello, World!');""", # 内联 JS"scripts.js" # 外部 JS]metas = [{"name": "viewport", "content": "width=device-width, initial-scale=1.0"},{"name": "author", "content": "Your Name"}]# 生成完整 HTML 页面print(render_html_page("My Page", page_content, styles=styles, scripts=scripts, metas=metas))