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/


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM