2014-02-26 91 views
1

我的python代碼生成一個列表和一個字符串字典。從python創建一個HTML頁面

我想創建一個HTML頁面並在表格中插入這些值。

我看了一下像yaptu模板引擎,但我需要更簡單的東西。

在此先感謝。

回答

0

也許你可以使用BeautifulSoup:

from bs4 import BeautifulSoup 

html = '<html><body><table>' 

for item in my_list: 
    html += '<tr>{0}</tr>'.format(str(item)) # this sort of thing 

for k, v in my_dict.iteritems(): 
    html += '<tr>{0}</tr>'.format(v) # or whatever 

html += '</table></body></html>' # now you have the full html string 

soup = BeautifulSoup(html) 

html = soup.prettify() # this would actually auto close unclosed tags for you too 

>>> print html 

<html> 
    <body> 
     <table> 
     <rows> 
     </rows> # etc. 
     </table> 
    </body> 
</html> 

信息上BeautifulSoup,它的docs

編輯:

至於您的評論

import os 

os.chdir(path) # will change your cwd to path if you have a specific one in mind 

要保存新生成的html文件到cwd:

with open('new.html', 'w') as f: # with will auto create file and close after writing 
    f.write(html) 
+0

這會在我的cwd中創建一個HTML文件嗎? – user3349548

+0

嗯,你沒有在你的問題中提到這個,所以沒有它不會,但請看我的編輯 – Totem

+0

非常感謝!這幾乎做了我的工作:) – user3349548

0

您可以使用內置Python的格式化功能,但你必須爲重複和類似的東西提供自己的代碼。相反,您可以使用一些簡單的模板機制,如mustache(Python版本被命名爲pystache)。