admin管理员组

文章数量:1130349

今天用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://wwwblogs/nx520zj/p/5865607.html

转载于:https://wwwblogs/qiututu/p/10329079.html

今天用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://wwwblogs/nx520zj/p/5865607.html

转载于:https://wwwblogs/qiututu/p/10329079.html

本文标签: 乱码中文正常显示器中文件