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


免責聲明!

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



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