今天用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