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/bootstrap@3.3.7/dist/css/bootstrap.min.css' rel='stylesheet'>"+'\n') f.write(data) f.write("<html>")
参考:
https://blog.csdn.net/weixin_42528089/article/details/94431244
https://www.bbsmax.com/A/kPzOrG7Qdx/
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
· 没有源码,如何修改代码逻辑?
· 分享4款.NET开源、免费、实用的商城系统
· 全程不用写代码,我用AI程序员写了一个飞机大战
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了
· 上周热点回顾(2.24-3.2)