‘壹’ 用python生成在html中显示的表格
可以通过写python脚本制作HTML的form,包括HTML的标签什么的
python 有个第三方库pyh用来生成HTML,可以试用一下:
from pyh import *
page = PyH('This is PyH page')
page << h1(cl='center', 'My big title')
table1 = page << table(border='1',id='mytable1')
headtr = table1 << tr(id='headline')
headtr << td('Head1') << td('Head2')
tr1 = table1 << tr(id='line1')
tr1 << td('r1,c1') <<td('r1,c2')
tr2 = table1 << tr(id='line2')
tr2 << td('r2,c1') <<td('r2,c2')
page.printOut()
‘贰’ python HTML展示表格数据(有合并的单元格)
拷贝一下代码并保存到本地,然后运行它,再打开那个Demo的链接就可以看到效果了
#!/usr/bin/envpython3
fromos.pathimportdirname,abspath,joinasjoinpath
L=[(1,2),(1,2),(1,3),(2,4),(2,5)]
column_names=('列名','数据')
odict=OrderedDict()
fork,vinL:
ifknotinodict:
odict[k]=[v]
else:
odict[k].append(v)
sa='''
<!DOCTYPEHTML>
<metacharset="UTF-8">
<html>
<body>
<tableborder="1"cellpadding="10">
<tr>
<th>{}</th>
<th>{}</th>
</tr>
'''.format(*column_names)
sc='''
</table>
</body>
</html>
'''
sb=[]
tdform='<tdalign="center">{}</td>'.format
fork,vinodict.items():
iflen(v)==1:
sb.append('<tr>')
sb.append(tdform(k))
sb.append(tdform(v))
sb.append('</tr>')
else:
fori,subvinenumerate(v):
sb.append('<tr>')
ifi==0:
sb.append('<tdrowspan="{}"align="center">{}</td>'.format(
len(v),k))
sb.append(tdform(subv))
sb.append('</tr>')
fn='table.html'
ss=sa+' '.join(sb)+sc
try:
frombs4importBeautifulSoup
soup=BeautifulSoup(ss)
ss=soup.prettify()
except:
pass
withopen(fn,'w')asf:
f.write(ss)
print(ss)
print('Demo:file://'+joinpath(abspath(dirname(__file__)),fn))
‘叁’ 怎么使用python来爬取网页上的表格信息
稍微说一下背景,当时我想研究蛋白质与小分子的复合物在空间三维结构上的一些规律,首先得有数据啊,数据从哪里来?就是从一个涵盖所有已经解析三维结构的蛋白质-小分子复合物的数据库里面下载。这时候,手动一个个去下显然是不可取的,我们需要写个脚本,能从特定的网站选择性得批量下载需要的信息。python是不错的选择。
import urllib #python中用于获取网站的模块
import urllib2, cookielib
有些网站访问时需要cookie的,python处理cookie代码如下:
cj = cookielib.CookieJar ( )
opener = urllib2.build_opener( urllib2.HttpCookieProcessor(cj) )
urllib2.install_opener (opener)
通常我们需要在网站中搜索得到我们需要的信息,这里分为二种情况:
1. 第一种,直接改变网址就可以得到你想要搜索的页面:
def GetWebPage( x ): #我们定义一个获取页面的函数,x 是用于呈递你在页面中搜索的内容的参数
url = 'http://xxxxx/xxx.cgi?&' + ‘你想要搜索的参数’ # 结合自己页面情况适当修改
page = urllib2.urlopen(url)
pageContent = page.read( )
return pageContent #返回的是HTML格式的页面信息
2.第二种,你需要用到post方法,将你搜索的内容放在postdata里面,然后返回你需要的页面
def GetWebPage( x ): #我们定义一个获取页面的函数,x 是用于呈递你在页面中搜索的内容的参数
url = 'http://xxxxx/xxx' #这个网址是你进入搜索界面的网址
postData = urllib.urlencode( { 各种‘post’参数输入 } ) #这里面的post参数输入需要自己去查
req= urllib2.Request (url, postData)
pageContent = urllib2.urlopen (req). read( )
return pageContent #返回的是HTML格式的页面信息
在获取了我们需要的网页信息之后,我们需要从获得的网页中进一步获取我们需要的信息,这里我推荐使用 BeautifulSoup 这个模块, python自带的没有,可以自行网络谷歌下载安装。 BeautifulSoup 翻译就是‘美味的汤’,你需要做的是从一锅汤里面找到你喜欢吃的东西。
import re # 正则表达式,用于匹配字符
from bs4 import BeautifulSoup # 导入BeautifulSoup 模块
soup = BeautifulSoup(pageContent) #pageContent就是上面我们搜索得到的页面
soup就是 HTML 中所有的标签(tag)BeautifulSoup处理格式化后的字符串,一个标准的tag形式为:
hwkobe24
通过一些过滤方法,我们可以从soup中获取我们需要的信息:
(1) find_all ( name , attrs , recursive , text , **kwargs)
这里面,我们通过添加对标签的约束来获取需要的标签列表, 比如 soup.find_all ('p') 就是寻找名字为‘p’的 标签,而soup.find_all (class = "tittle") 就是找到所有class属性为"tittle" 的标签,以及soup.find_all ( class = re.compile('lass')) 表示 class属性中包含‘lass’的所有标签,这里用到了正则表达式(可以自己学习一下,非常有用滴)
当我们获取了所有想要标签的列表之后,遍历这个列表,再获取标签中你需要的内容,通常我们需要标签中的文字部分,也就是网页中显示出来的文字,代码如下:
tagList = soup.find_all (class="tittle") #如果标签比较复杂,可以用多个过滤条件使过滤更加严格
for tag in tagList:
print tag.text
f.write ( str(tag.text) ) #将这些信息写入本地文件中以后使用
(2)find( name , attrs , recursive , text , **kwargs )
它与 find_all( ) 方法唯一的区别是 find_all() 方法的返回结果是值包含一个元素的列表,而 find() 方法直接返回结果
(3)find_parents( ) find_parent( )
find_all() 和 find() 只搜索当前节点的所有子节点,孙子节点等. find_parents() 和 find_parent() 用来搜索当前节点的父辈节点,搜索方法与普通tag的搜索方法相同,搜索文档搜索文档包含的内容
(4)find_next_siblings() find_next_sibling()
这2个方法通过 .next_siblings 属性对当 tag 的所有后面解析的兄弟 tag 节点进代, find_next_siblings() 方法返回所有符合条件的后面的兄弟节点,find_next_sibling() 只返回符合条件的后面的第一个tag节点
(5)find_previous_siblings() find_previous_sibling()
这2个方法通过 .previous_siblings 属性对当前 tag 的前面解析的兄弟 tag 节点进行迭代, find_previous_siblings()方法返回所有符合条件的前面的兄弟节点, find_previous_sibling() 方法返回第一个符合条件的前面的兄弟节点
(6)find_all_next() find_next()
这2个方法通过 .next_elements 属性对当前 tag 的之后的 tag 和字符串进行迭代, find_all_next() 方法返回所有符合条件的节点, find_next() 方法返回第一个符合条件的节点
(7)find_all_previous() 和 find_previous()
这2个方法通过 .previous_elements 属性对当前节点前面的 tag 和字符串进行迭代, find_all_previous() 方法返回所有符合条件的节点, find_previous()方法返回第一个符合条件的节点
具体的使用方法还有很多,用到这里你应该可以解决大部分问题了,如果要更深入了解可以参考官方的使用说明哈!
‘肆’ Python web实现Excel数据下载
python3;flask;
样例使用的是pandas这个包,有点大财小用。建议普通项目用excel专用包即可。
‘伍’ python能用来制作表格吗
可以的,python有很多扩展模块
比如xlwt、xlrd等等,可以用作xls表格文件的读写处理
完全可以实现表格制作功能
‘陆’ python怎么动态生成html表格报告
..conn = sqlite3.connect(database='thedbfile')curr = conn.cursor()curr.execute("select * from thetable") tr1 = table1 << tr(id="header")for field in curr.description: tr1 << th(field[0]) for row in curr: tr2 = table1 << tr() for item in row: tr2 << td(item) curr.close()conn.close()...以上代码基于1L"就是累w_w"的方案进行完善
‘柒’ python怎样做html的表格
现要实现python制作html格式的表格,利用Python对字符串str.format()格式化操作进行处理,在日常对CVS格式文件处理过程当中,经常会将CVS格式文件进行转换,在正式场合是程序读取CVS文件进行转换并输出到html格式的文件当中,但现在只是实现一下转换的过程,需要输入以逗号分隔的数据。
在设计程式的时候,需要先定义一下整个代码的框架,首先我们要定义一个主函数main(),虽然Python没有规定入口函数,一般在正式的开发中都设计了一个main()函数作为程序的入口函数,或许这是一种规范吧。然后我们在定义一个打印表头的方法print_head(),并在主函数里进行调用。再定义一个打印表尾的方法print_end(),也在主函数中进行调用。定义print_line()为打印表格行,定义extract_field()处理cvs行数据转换为list集合数据。最后再定义一个处理特殊符号的方法escape_html(),因为在html代码中为了避免与它的标签冲突,特要进行特殊符号的转换,如&-->&
还有就是对长度过长的数据要进行处理并用...代替
源代码:
#Author Tandaly
#Date 2013-04-09
#File Csv2html.py
#主函数
def main():
print_head()
maxWidth = 100
count = 0
while True:
try:
line = str(input())
if count == 0:
color = "lightgreen"
elif count%2 == 0:
color = "white"
else:
color = "lightyellow"
print_line(line, color, maxWidth)
count += 1
except EOFError:
break
print_end()
#打印表格头
def print_head():
print("")
#打印表行
def print_line(line, color, maxWidth):
tr = "".format(color)
tds = ""
if line is not None and len(line) > 0:
fields = axtract_fields(line)
for filed in fields:
td = "{0}".format(filed if (len(str(filed)) <= maxWidth) else
(str(filed)[:100] + "..."))
tds += td
tr += "{0}
".format(tds)
print(tr)
#打印表格尾
def print_end():
print("")
#抽取行值
def axtract_fields(line):
line = escape_html(line)
fields = []
field = ""
quote = None
for c in line:
if c in "\"":
if quote is None:
quote = c
elif quote == c:
quote = None
continue
if quote is not None:
field += c
continue
if c in ",":
fields.append(field)
field = ""
else:
field += c
if len(field) > 0:
fields.append(field)
return fields
#处理特殊符号
def escape_html(text):
text = text.replace("&", "&")
text = text.replace(">", ">")
text = text.replace("<", "<")
return text
#程序入口
if __name__ == "__main__":
main()
运行结果:
>>>
"nihao","wo"
nihaowo
"sss","tandaly"
...tandaly
"lkkkkkkkkkkksdfssssssssssssss",
34
...34
‘捌’ Python怎么抓取表格 正则怎么写
看了你的正则表达式。思路基本上是正则的。不过有些小问题。我建议你初学的时候分两步搜索。
先找到所有的tr,再在tr里找td
exp1=re.compile("(?isu)<tr[^>]*>(.*?)</tr>")
exp2=re.compile("(?isu)<td[^>]*>(.*?)</td>")
htmlSource=urllib.urlopen("http://cn-proxy.com/").read()
forrowinexp1.findall(htmlSource):
print'==============='
forcolinexp2.findall(row):
printcol,
这里(?isu)意思就是,要搜索时,包含回车换行,包含汉字,包含空格。
你多试试。找一个正则表达式验证工具,比如kodos。 然后看看python自带的那个正则表达式教程就可以了。
‘玖’ 请问python如何使用tk绘制图片这种表格,并且可以在空白处添加数据后保存文件
这明显不是 tk 干的活啊。 这应该是一张web 表格,或者 WORD 模板 才合适。