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()
原文地址:https://www.cnblogs.com/nx520zj/p/5865607.html