1. 程式人生 > >Python之生成HTML檔案

Python之生成HTML檔案

在做影象處理時會有結果資料生成,一種好的方法是將結果儲存為HTML檔案,在檔案中插入圖片的超連結,就可以在網頁中同時顯示結果和圖片。因此,本文對Python生成HTML的方法做一個總結。

1 簡單示例

#coding:utf-8

import webbrowser
#命名生成的html
GEN_HTML = "test.html" 
#開啟檔案,準備寫入
f = open(GEN_HTML,'w')

#準備相關變數
str1 = 'my name is :'
str2 = '--zongxp--'

message = """
<html>
<head></head>
<body>
<p>%s</p>
<p>%s</p>
</body>
</html>"""%(str1,str2)

#寫入檔案
f.write(message) 
#關閉檔案
f.close()

#執行完自動在網頁中顯示
webbrowser.open(GEN_HTML,new = 1) 
'''
webbrowser.open(url, new=0, autoraise=True) 
Display url using the default browser. If new is 0, the url is opened in the same browser window if possible. If new is 1, a new browser window is opened if possible. If new is 2, a new browser page (“tab”) is opened if possible. If autoraise is True, the window is raised if possible (note that under many window managers this will occur regardless of the setting of this variable).
'''