練習 XML to HTML
<books>
<book>
<title>The Great Gatsby</title>
<author>F. Scott Fitzgerald</author>
<year>1925</year>
</book>
<book>
<title>To Kill a Mockingbird</title>
<author>Harper Lee</author>
<year>1960</year>
</book>
</books>
'''
練習題目:
將上述XML資料轉換成HTML格式,
生成一個簡單的書籍清單網頁.
'''
import xml.etree.ElementTree as et
tree=et.ElementTree(file='books.xml')
root=tree.getroot()
#生成HTML
html="<html><body><h1>書籍清單</h1><ul>"
for book in root:
title=book.find('title').text
author=book.find('author').text
year=book.find('year').text
html +=f'<li>{title} - {author}({year})</li>'
html += "</ul></body></html>"
#將HTML 寫入檔案
with open('book_list.html','w',encoding='utf-8')as file:
file.write(html)
#指定encoding='utf-8'參數 已指定使用UTF-8編碼,確保HTML文件以UTF-8編碼保存,支持各種語言的文字
#生成的HTML文件使用UTF-8 編碼保存,確保文字能正確顯示
標籤: 練習


0 個意見:
張貼留言
訂閱 張貼留言 [Atom]
<< 首頁