python如何将数据生成html文件+浏览器中文显示乱码问题

需求:从msysql数据库查询数据,并生成html文件,后自动发送邮件(html格式),在网上找了许久,终于找到2种解决方法!

一、近来在网上采集数据,想把采集下来的数据整合成html的形式保存。以便其他的平台产品可以直接读取html显示或者根据html标签提取数据。

    def output_html(self):
        try:
            fout = open('output.html','w')
            fout.write("<html>")
            fout.write("<body>")
            fout.write("<table>")
            for data in self.datas:
                fout.write("<tr>")
                fout.write("<td>%s</td>" % data['url'])
                fout.write("<td>%s</td>" % data['title'].encode('utf-8'))
                fout.write("<td>%s</td>" % data['summary'].encode('utf-8'))
                fout.write("</tr>")
            fout.write("</table>")
            fout.write("</body>")
            fout.write("</html>")
        finally:
            if f:
                fout.close()

但是发现生成后的output.html,用IE浏览器打开html文件时,中文字体显示乱码。后来发现IE浏览器可以设置编码,直接设置为UTF8之后,中文显示正常。

那么,如果在html中添加一些元素,让浏览器知道以哪种编码打开文件呢?html添加这句代码 ****。

    def output_html(self):
        try:
            fout = open('output.html','w')
            fout.write("<html>")
            #添加如下这句html代码让浏览器知道要什么编码显示
            fout.write("<meta charset=\"utf-8\">")
            fout.write("<body>")
            fout.write("<table>")
            for data in self.datas:
                fout.write("<tr>")
                fout.write("<td>%s</td>" % data['url'])
                fout.write("<td>%s</td>" % data['title'].encode('utf-8'))
                fout.write("<td>%s</td>" % data['summary'].encode('utf-8'))
                fout.write("</tr>")
            fout.write("</table>")
            fout.write("</body>")
            fout.write("</html>")
        finally:
            if f:
                fout.close()

二、使用pandas处理数据

#!/usr/bin/python
# coding: utf-8
import pandas as pd

def convertToHtml(result, title):
    # 将数据转换为html的table
    # result是list[list1,list2]这样的结构
    # title是list结构;和result一一对应。titleList[0]对应resultList[0]这样的一条数据对应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("<html>"+'\n')
        f.write("<meta charset='utf-8'>"+'\n')
        f.write("<link href='https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css' rel='stylesheet'>"+'\n')
        f.write(data)
        f.write("<html>")

猜你喜欢

转载自www.cnblogs.com/hanfe1/p/12574833.html