python生成html文件在pycharm中正常顯示,在瀏覽器中打開中文亂碼

今天用python(版本3.5)將爬取的數據寫入html文件中,代碼以下: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>")

 

發現數據在控制檯輸出正常,以下圖:python

然而在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.htmlurl

相關文章
相關標籤/搜索