python生成html文件瀏覽器中文顯示亂碼問題


近來在網上采集數據,想把采集下來的數據整合成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添加這句代碼 <meta charset="utf-8">

    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()

 


免責聲明!

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



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