近來在網上采集數據,想把采集下來的數據整合成html的形式保存。以便其他的平台產品可以直接讀取html顯示或者根據html標簽提取數據。
def output_html(self): try: fout = open('output.html','w') fout.write("<html>") fout.write("<body>") fout.write("<table>") for data in self.datas: fout.write("<tr>") fout.write("<td>%s</td>" % data['url']) fout.write("<td>%s</td>" % data['title'].encode('utf-8')) fout.write("<td>%s</td>" % data['summary'].encode('utf-8')) fout.write("</tr>") fout.write("</table>") fout.write("</body>") fout.write("</html>") finally: if f: fout.close()
但是發現生成后的output.html,用IE瀏覽器打開html文件時,中文字體顯示亂碼。后來發現IE瀏覽器可以設置編碼,直接設置為UTF8之后,中文顯示正常。
那么,如果在html中添加一些元素,讓瀏覽器知道以哪種編碼打開文件呢?html添加這句代碼 <meta charset="utf-8">。
def output_html(self): try: fout = open('output.html','w') fout.write("<html>") #添加如下這句html代碼讓瀏覽器知道要什么編碼顯示 fout.write("<meta charset=\"utf-8\">") fout.write("<body>") fout.write("<table>") for data in self.datas: fout.write("<tr>") fout.write("<td>%s</td>" % data['url']) fout.write("<td>%s</td>" % data['title'].encode('utf-8')) fout.write("<td>%s</td>" % data['summary'].encode('utf-8')) fout.write("</tr>") fout.write("</table>") fout.write("</body>") fout.write("</html>") finally: if f: fout.close()