Home | 简体中文 | 繁体中文 | 杂文 | Github | 知乎专栏 | Facebook | Linkedin | Youtube | 打赏(Donations) | About
知乎专栏

6.4. Dominate

Dominate is a Python library for creating and manipulating HTML documents using an elegant DOM API. It allows you to write HTML pages in pure Python very concisely, which eliminates the need to learn another template language, and lets you take advantage of the more powerful features of Python.

https://pypi.org/project/dominate/

	
pip install dominate
	
	

6.4.1. 创建一个 HTML

		
import dominate
from dominate.tags import *

doc = dominate.document(title='Dominate your HTML')

with doc.head:
    link(rel='stylesheet', href='style.css')
    script(type='text/javascript', src='script.js')

with doc:
    with div(id='header').add(ol()):
        for i in ['home', 'about', 'contact']:
            li(a(i.title(), href='/%s.html' % i))

    with div():
        attr(cls='body')
        p('Lorem ipsum..')

print(doc)
		
		
		
		
/Users/neo/PycharmProjects/netkiller/.venv/bin/python /Users/neo/PycharmProjects/netkiller/test/html.py 
<!DOCTYPE html>
<html>
  <head>
    <title>Dominate your HTML</title>
    <link href="style.css" rel="stylesheet">
    <script src="script.js" type="text/javascript"></script>
  </head>
  <body>
    <div id="header">
      <ol>
        <li>
          <a href="/home.html">Home</a>
        </li>
        <li>
          <a href="/about.html">About</a>
        </li>
        <li>
          <a href="/contact.html">Contact</a>
        </li>
      </ol>
    </div>
    <div class="body">
      <p>Lorem ipsum..</p>
    </div>
  </body>
</html>		
		
		

6.4.2. dominate

		
from dominate import document
d = document()
d +=h1('Hello,World!')
d.body+=p('This is a paragraph.')
print(d)		
		
		
		
<!DOCTYPE html>
<html>
  <head>
    <title>Dominate</title>
  </head>
  <body>
    <h1>Hello,World!</h1>
    <p>This is a paragraph.</p>
  </body>
</html>		
		
		

6.4.3. HTML Table

		
import dominate
from dominate.tags import *

# 创建一个 HTML 文档
doc = dominate.document(title='表格示例')

with doc.body:
    h1('数据表格 by netkiller - https://www.netkiller.cn')
    with table().add(tbody()):
        for i in range(5):
            with tr():
                for j in range(3):
                    td(f'单元格 {i},{j}')

# 打印 HTML 文档
print(doc)
		
		
		

6.4.4. UL/LI

		
# 创建一个 HTML 文档
doc = dominate.document(title='项目符号列表 by netkiller - https://www.netkiller.cn')
 
# 动态数据
items = ['苹果', '香蕉', '橙子']
 
with doc.body:
    h1('水果列表')
    with ul():
        for item in items:
            li(item)
 
# 打印 HTML 文档
print(doc)		
		
		

6.4.5. Dominate 与 Flask 集成

生成动态网页内容

		
from flask import Flask
import dominate
from dominate.tags import *
 
app = Flask(__name__)
 
@app.route('/')
def index():
    doc = dominate.document(title='Flask 与 Dominate 集成 by netkiller - https://www.netkiller.cn')
 
    with doc.head:
        link(rel='stylesheet', href='/static/style.css')
 
    with doc.body:
        h1('Hello, Flask & Dominate!')
        p('这是一段由 Flask 和 Dominate 生成的文本。')
 
    return str(doc)
 
if __name__ == '__main__':
    app.run(debug=True)		
		
		

6.4.6. 装饰器

		
@div(h2('Welcome'),cls='greeting')
... def greeting(name):
...     p('Hello %s' %name)
...     
print(greeting('Bob'))

输出:

<div class="greeting">
  <h2>Welcome</h2>
  <p>Hello Bob</p>
</div>		
		
		

6.4.7. HTML 标记

6.4.7.1. html()

			
print(html(body(h1('Hello, World!'))))			
			
			

输出

			
<html>
  <body>
    <h1>hello,world</h1>
  </body>
</html>			
			
			
			
_html=html()
_body=_html.add(body())
header=_body.add(div(id='header'))
content=_body.add(div(id='content'))
footer=_body.add(div(id='footer'))
print(_html)			
			
			
			
<html>
  <body>
    <div id="header"></div>
    <div id="content"></div>
    <div id="footer"></div>
  </body>
</html>	
			
			
			
			
			
from dominate.tags import *
h = html()

with h.add(body()).add(div(id='content')):
    h1('Hello World!')
    p('This is my first html.')
    with table().add(tbody()):
        l=tr()
        l +=td('One')
        l.add(td('Two'))
        with l:
            td('Three')
with open('test.html','w') as f:
    f.write(h.render())