This is the 22nd day of my participation in the August Wen Challenge.More challenges in August
Earlier, the committee wrote a screenshot of the top list crawler.
Many readers left comments that the hot list screenshots are not very good analysis, do a list more intuitive. Yes, it is so let’s take a look at generating HTML pages using only Python.
At dominate, we want to create a magic ‘dominate’ image:
This tutorial teaches you to dominate from 0!
What is the dominate
A Python library that allows developers to write and construct HTML/document trees using pure Python programming, supporting elegant tag context concatenation and intuitive writing of HTML pages. So, it’s ok if you don’t know HTML, which is pretty straightforward.
Install and use
The installation
pip install dominate
Copy the code
Save the following code as basic_html.py and run it.
from dominate.tags import *
print(html(body(h1('Thunder academy Dmoniate Demo! '))))
Copy the code
That’s it. The HTML page content has been generated.
Look at the black HTML output above to read the code:
- Code needs to be read from the inside out
- H1 block tag generation with built-in text: Dominate Demo!
- Generate the body tag, where the H1 tag object is passed into the body function, so it needs to be displayed with the H1 tag
- Generate an HTML tag, where the body is passed into the HTML function, and we need to display the body.
End of reading.
Save the web page as a report file
from dominate.tags import *
_html = html(body(h1('Thunder academy Dmoniate Demo! ')))
print(_html)
with open('./report.html'.'w') as file:
file.write(_html.render())
Copy the code
The dominant render function is called to generate the string content and output it to a file.
This is done, small white institute can directly to the committee three even.
Play at Dominate
Further basic operations are as follows, directly with the picture to see the code.
""" Thunder committee Demo code, remember the three support!" ""
from dominate.tags import *
print(html(body(h1('Thunder academy Dmoniate Demo! '))))
Generate div block tag with row_id attribute
user_label = label("username", cls='classname leiXueWei', fr='someinput')
print(user_label)
Generate div block tag with row_id attribute
data_div = div(row_id="001")
print(data_div)
Generate a div block tag with id header
header = div()
header['id'] = 'header'
print(header)
Copy the code
Save the above content as basic_html.py run, the corresponding effect is as follows
Advanced operation
This is more difficult, but can make more complex pages. And can make HTML pages more elegant, don’t you want to take some time to look?
Take another 5 minutes to bring the Dominate home directly!
Advanced operation skills are necessary
Save the following code as complex_html_01.py and run it.
"""Thunder committee Demo code, remember three support!"""
from dominate.tags import *
# Try iteratively building ul tag blocks
list = ul()
for item in range(6):
list += li(Item # of the Lei Committee, item)
print(list)
# Streaming programming style
leixuewei_menus = [
{"name":"Home"."link":"/home"},
{"name":"LXW"."link":"/leiXueWei"},
{"name":"About"."link":"/about"}]#leixuewei_menus.append({"name":"Home","link":"/home"})
print(ul(li(a(item['name'], href=item['link']), __pretty=False) for item in leixuewei_menus))
# A simple document tree structure
_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)
# clean code
_html = html()
_head, _body = _html.add(head(title('Simple Document Tree -Document Tree')), body())
names = ['header'.'content'.'footer']
header, content, footer = _body.add([div(id=name) for name in names])
print(_html)
Get the formatted HTML with render
a = div(span('Hello World'))
print(a.render())
"""LeiXueWei Demo code, I'll give you a damn."""
Copy the code
I gave it to the code, and I gave it to you. Must follow this picture to see the code, learning efficiency double! (PS: The same goes for the technical blog of the Academy.)
Finally, take a look at the elegant code and decorator
I have to, because it makes writing code so much more elegant.
Save the following code as complex_html_02.py and run it.
"""Thunder committee Demo code, remember three support!"""
from dominate.tags import *
# Use With context management to write more intuitive
h = html()
with h.add(body()).add(div(id='content')):
h1('Hello World! ')
p(Welcome to the Lei School Committee, learn together... ')
with table().add(tbody()):
l = tr()
l += td('One')
l.add(td('Two'))
with l:
td('Three')
print(h)
Use modifiers to make code more concise and readable
""Def greeting(name): with div() as d: p()Hello %s" % name) return d """
@div
def greeting(name):
p('Hello %s' % name)
print(greeting("Leivn"))
@div(h2('Welcome'), cls='greeting')
def greeting(name):
p('Hello %s' % name)
print(greeting('Levin'))
from dominate import document
Create a document
d = document()
print(d)
# Standard HTML document
d = document()
d += h1('Hello, World! ')
d += p('This is a paragraph.')
print(d)
# Support native HTML embedding
from dominate.util import raw
td(raw('<a href="example.html">Example</a>'))
# to create SVG
from dominate.svg import *
print(circle(stroke_width=5))
"""LeiXueWei Demo code, brothers are white piao so much, pay attention to three even support it!"""
Copy the code
This is more code and more elegant. The emphasis is on the with context style, and the @ decorator. The rest of the code belongs to a more functional presentation.
Run the following effect, no longer cut up the image, that look not too good, leave some time to write a new article. The above operation is also much more complex, chopped up, suggest with the picture to see the code.
It’s actually complex01 and complex02, but you can split them up.
This article doesn’t need a summary, it needs a lot of programming practice, let’s go.
By the way, the committee also has this can pay attention to long-term reading => Thunder committee interesting programming story compilation
Or => Ray academy NodeJS long series
Continuous learning and continuous development, I am Lei Xuewei! Programming is fun. The key is to get the technology right. Creation is not easy, please support, like collection support committee!