python生成html文件在pycharm中正常显示,在浏览器中打开中文乱码

今天用python(版本3.5)将爬取的数据写入html文件中,代码如下:

        fout=open('output1.html','w',encoding='utf-8')
        fout.write("<html>")
        fout.write("<body>")
        fout.write("<table>")
        for data in self.datas:
            fout.write("<tr>")
            #print(data['summary'])
            fout.write("<td>%s</td>"%data['url'])
            #print(data['title'])
            fout.write("<td>%s</td>" % data['title'])
            fout.write("<td>%s</td>" % data['summary'])
            fout.write("</tr>")
        fout.write("</table>")
        fout.write("</body>")
        fout.write("</html>")

发现数据在控制台输出正常,如下图:

然而在edge浏览器打开时,中文部分全是乱码。如下图:

通过查询资料后,获得正确的解决方案为在html和body之间插入一句:

fout.write("<meta charset=\"utf-8\">")告诉浏览器打开文件的编码方式
如下所示
        fout=open('output.html','w',encoding='utf-8')
        fout.write("<html>")
        fout.write("<meta charset=\"utf-8\">")
        fout.write("<body>")
        fout.write("<table>")

 参考博客链接:https://www.cnblogs.com/nx520zj/p/5865607.html

猜你喜欢

转载自www.cnblogs.com/qiututu/p/10329079.html