使用Python自动生成HTML的方法示例

yipeiwu_com5年前Python基础

python 自动化批量生成前端的HTML可以大大减轻工作量

下面演示两种生成 HTML 的方法

方法一:使用 webbrowser

#coding:utf-8
 
import webbrowser
#命名生成的html
GEN_HTML = "test.html" 
#打开文件,准备写入
f = open(GEN_HTML,'w')
 
#准备相关变量
str1 = 'my name is :'
str2 = '--MichaelAn--'
 
# 写入HTML界面中
message = """
<html>
<head></head>
<body>
<p>%s</p>
<p>%s</p>
</body>
</html>
"""%(str1,str2)
 
#写入文件
f.write(message) 
#关闭文件
f.close()
 
#运行完自动在网页中显示
webbrowser.open(GEN_HTML,new = 1) 
'''
webbrowser.open(url, new=0, autoraise=True) 
Display url using the default browser. If new is 0, the url is opened in the same browser window if possible. If new is 1, a new browser window is opened if possible. If new is 2, a new browser page (“tab”) is opened if possible. If autoraise is True, the window is raised if possible (note that under many window managers this will occur regardless of the setting of this variable).
'''

方法二:使用pyh

#coding:utf-8
from pyh import *
# there is a bug "from pyh import *"
page = PyH('My wonderful PyH page')
page.addCSS('myStylesheet1.css', 'myStylesheet2.css')
page.addJS('myJavascript1.js', 'myJavascript2.js')
page << h1('My big title', cl='center')
page << div(cl='myCSSclass1 myCSSclass2', id='myDiv1') << p('I love PyH!', id='myP1')
mydiv2 = page << div(id='myDiv2')
mydiv2 << h2('A smaller title') + p('Followed by a paragraph.')
page << div(id='myDiv3')
page.myDiv3.attributes['cl'] = 'myCSSclass3'
page.myDiv3 << p('Another paragraph')
page.printOut('a.html')

对于大型的 HTML ,使用方法一可以跟灵活的处理HTML的元素变化。在这里推荐使用方法一生成HTML。

下面是生成的html

<html>
<head></head>
<body>
<p>my name is :</p>
<p>--MichaelAn--</p>
</body>
</html>

这样的方法可以生成简单的HTML,这种使用python自动生成HTML的思想需要有。未来使用人工智能等技术,可以根据已有网站进行深度学习,从而自动绘制新的网站。所以,前端工程化和未来发展需要重视。

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持【听图阁-专注于Python设计】。

相关文章

Python redis操作实例分析【连接、管道、发布和订阅等】

本文实例讲述了Python redis操作。分享给大家供大家参考,具体如下: 一、redis redis是一个key-value存储系统。和Memcached类似,它支持存储的value...

对Python 语音识别框架详解

如下所示: from win32com.client import constants import os import win32com.client import pythonc...

Python探索之静态方法和类方法的区别详解

面相对象程序设计中,类方法和静态方法是经常用到的两个术语。 逻辑上讲:类方法是只能由类名调用;静态方法可以由类名或对象名进行调用。 python staticmethod and cla...

Python collections中的双向队列deque简单介绍详解

前言 在python神书《Python+Cookbook》中有这么一段话:在队列两端插入或删除元素时间复杂度都是 O(1) ,而在列表的开头插入或删除元素的时间复杂度为 O(N)。 于...

python自然语言编码转换模块codecs介绍

python对多国语言的处理是支持的很好的,它可以处理现在任意编码的字符,这里深入的研究一下python对多种不同语言的处理。 有一点需要清楚的是,当python要做编码转换的时候,会借...