python 生成html文件浏览器_python如何将数据生成html文件+浏览器中文显示乱码问题...
需求:從msysql數(shù)據(jù)庫查詢數(shù)據(jù),并生成html文件,后自動發(fā)送郵件(html格式),在網(wǎng)上找了許久,終于找到2種解決方法!
一、近來在網(wǎng)上采集數(shù)據(jù),想把采集下來的數(shù)據(jù)整合成html的形式保存。以便其他的平臺產(chǎn)品可以直接讀取html顯示或者根據(jù)html標(biāo)簽提取數(shù)據(jù)。
def output_html(self):
try:
fout = open('output.html','w')
fout.write("")
fout.write("
")fout.write("
for data in self.datas:
fout.write("
")fout.write("
%s" % data['url'])fout.write("
%s" % data['title'].encode('utf-8'))fout.write("
%s" % data['summary'].encode('utf-8'))fout.write("
")fout.write("
")fout.write("")
fout.write("")
finally:
if f:
fout.close()
但是發(fā)現(xiàn)生成后的output.html,用IE瀏覽器打開html文件時,中文字體顯示亂碼。后來發(fā)現(xiàn)IE瀏覽器可以設(shè)置編碼,直接設(shè)置為UTF8之后,中文顯示正常。
那么,如果在html中添加一些元素,讓瀏覽器知道以哪種編碼打開文件呢?html添加這句代碼 ****。
def output_html(self):
try:
fout = open('output.html','w')
fout.write("")
#添加如下這句html代碼讓瀏覽器知道要什么編碼顯示
fout.write("")
fout.write("
")fout.write("
for data in self.datas:
fout.write("
")fout.write("
%s" % data['url'])fout.write("
%s" % data['title'].encode('utf-8'))fout.write("
%s" % data['summary'].encode('utf-8'))fout.write("
")fout.write("
")fout.write("")
fout.write("")
finally:
if f:
fout.close()
二、使用pandas處理數(shù)據(jù)
#!/usr/bin/python
# coding: utf-8
import pandas as pd
def convertToHtml(result, title):
# 將數(shù)據(jù)轉(zhuǎn)換為html的table
# result是list[list1,list2]這樣的結(jié)構(gòu)
# title是list結(jié)構(gòu);和result一一對應(yīng)。titleList[0]對應(yīng)resultList[0]這樣的一條數(shù)據(jù)對應(yīng)html表格中的一列
d = {}
index = 0
for t in title:
d[t] = result[index]
index = index + 1
df = pd.DataFrame(d)
df = df[title]
h = df.to_html(index=False)
return h
if __name__ == '__main__':
result = [[u'2016-08-25', u'2016-08-26', u'2016-08-27'], [u'張三', u'李四', u'王二']]
title = [u'日期', u'姓名']
data=convertToHtml(result, title)
with open('ribao.html','w',encoding='utf-8') as f:
f.write(""+'\n')
f.write(""+'\n')
f.write(""+'\n')
f.write(data)
f.write("")
總結(jié)
以上是生活随笔為你收集整理的python 生成html文件浏览器_python如何将数据生成html文件+浏览器中文显示乱码问题...的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: les物流执行系统_物流LES系统上线啦
- 下一篇: execjs回调python_pytho