{ "cells": [ { "cell_type": "markdown", "metadata": {}, "source": [ "# `html5tagger` 快速上手\n", "\n", "安装:\n", "\n", "```bash\n", "pip install html5tagger\n", "```\n", "\n", "`html5tagger` 提供了两个 HTML 生成的起点:`E` 用于创建空的构建器来生成 HTML 片段,或者 `Document` 用于生成带有 `DOCTYPE` 声明的完整 HTML 文档。两者都会产生 `Builder` 对象,以防你需要它进行类型注解。\n", "\n", "通过点表示法创建片段并添加标签:\n", "\n", "```python \n", "E.p(\"Powered by:\").br.a(href=\"...\")(\"html5tagger\")\n", "```\n", "\n", "生成:\n", "\n", "```html\n", "
Powered by:
html5tagger\n",
"```"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## `html5tagger` 简单示例"
]
},
{
"cell_type": "code",
"execution_count": 1,
"metadata": {},
"outputs": [],
"source": [
"from html5tagger import Document, E"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"创建 `document`:"
]
},
{
"cell_type": "code",
"execution_count": 2,
"metadata": {},
"outputs": [],
"source": [
"doc = Document(\n",
" E.TitleText_, # 第一个参数是用于 `
A paragraph with a link and formatting" ], "text/plain": [ "《Document Builder》\n", "
A paragraph with a link and formatting" ] }, "execution_count": 5, "metadata": {}, "output_type": "execute_result" } ], "source": [ "doc.p(\"A paragraph with \").a(\"a link\", href=\"/files\")(\" and \").em(\"formatting\")" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "对于复杂的嵌套(通常不需要)使用 {data}`with`。" ] }, { "cell_type": "code", "execution_count": 6, "metadata": {}, "outputs": [], "source": [ "with doc.table(id=\"data\"):\n", " doc.tr.th(\"First\").th(\"Second\").th(\"Third\")\n", " doc.TableRows_" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "在模板变量中添加一些东西:" ] }, { "cell_type": "code", "execution_count": 7, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "\n" ] } ], "source": [ "print(doc.Head._script(\"console.log(' escaping is weird')\"))" ] }, { "cell_type": "code", "execution_count": 9, "metadata": {}, "outputs": [], "source": [ "table = doc.TableRows\n", "for row in range(10):\n", " table.tr\n", " for col in range(3):\n", " table.td(row * col)" ] }, { "cell_type": "code", "execution_count": 10, "metadata": {}, "outputs": [ { "data": { "text/html": [ "
A paragraph with a link and formatting
First | Second | Third |
---|---|---|
0 | 0 | 0 |
0 | 1 | 2 |
0 | 2 | 4 |
0 | 3 | 6 |
0 | 4 | 8 |
0 | 5 | 10 |
0 | 6 | 12 |
0 | 7 | 14 |
0 | 8 | 16 |
0 | 9 | 18 |
A paragraph with a link and formatting
First | Second | Third《TableRows: |
---|---|---|
0 | 0 | 0< ···》 |
A paragraph with a link and formatting
First | Second | Third |
---|
A paragraph with a link and formatting
First | Second | Third《TableRows》 |
---|
A paragraph with a link and formatting
First | Second | Third |
---|
` 这样的元素不需要任何闭合标签,因此我们可以不断添加内容而不必担心何时应该关闭。对于可选或禁止使用闭合标签的元素,此模块不使用闭合标签。\n", "\n", "当您向一个元素添加内容或添加另一个标签时,该元素会自动闭合。仅仅设置属性并不会关闭一个元素。如果后续的任何内容都不应该在它内部,则可以使用(`None`)来关闭空元素,例如 `doc.script(None, src=\"...\")`。\n", "\n", "对于像 `