Python应用phy模块生成html表格

phy是一个用来生成html页面的Python模块,使用面向对象的方式,html的标签都会对应一个Python的对象,输出的html文档排版良好,易于阅读。

phy模块下载即安装使用方法,详见:http://down.51cto.com/data/2069383


下面的例子用于根据列表中的值生成html表格,代码例子中用到的关于html知识的解释如下:

style表示样式,text-align为文字位置属性,center表示居中;

margin属性用于设置各边上外边距的宽度,后面的参数依次表示top、right、bottom、left,auto,表示上下左右根据宽度自适应相同值,即居中;

cellspacing属性用来指定表格各单元格之间的空隙。此属性的参数值是数字,表示单元格间隙所占的像素点数;

cellpadding属性用来指定单元格内容与单元格边界之间的空白距离的大小。此属性的参数值也是数字,表示单元格内容与上下边界之间空白距离的高度所占像素点数以及单元格内容与左右边界之间空白距离的宽度所占的像素点数。

from pyh import *
list=[[1,'Lucy',25],[2,'Tom',30],[3,'Lily',20]]
page = PyH('Test')
page<<div(style="text-align:center")<<h4('Test table')
mytab = page << table(border="1",cellpadding="3",cellspacing="0",style="margin:auto")
tr1 = mytab << tr(bgcolor="lightgrey")
tr1 << th('id') + th('name')+th('age')
for i in range(len(list)):
    tr2 = mytab << tr()
    for j in range(3):
        tr2 << td(list[i][j])
        if list[i][j]=='Tom':
            tr2.attributes['bgcolor']='yellow'
        if list[i][j]=='Lily':
            tr2[1].attributes['style']='color:red'
page.printOut('test.html')

运行后生成的test.html的效果图:

wKioL1Wqc8nS6RJyAADUaIrzQNc288.jpg

你可能感兴趣的:(python,PHY)