我正在寻找一种在python中动态创建html文件的方法.我正在编写一个库脚本,它遍历目录,收集文件元数据.我打算然后使用这些数据自动创建一个基于html的图片库.非常简单的东西,只是一张图片表.
我真的不认为手动写文件是最好的方法,而且代码可能很长.那么有没有更好的方法来做到这一点,可能是html特定的?
Kni*_*nio 41
Dominate是一个Python库,用于直接在代码中创建HTML文档和片段,而无需使用模板.您可以使用以下内容创建一个简单的图库:
import glob
from dominate import document
from dominate.tags import *
photos = glob.glob('photos/*.jpg')
with document(title='Photos') as doc:
    h1('Photos')
    for path in photos:
        div(img(src=path), _class='photo')
with open('gallery.html', 'w') as f:
    f.write(doc.render())
输出:
<!DOCTYPE html>
<html>
  <head>
    <title>Photos</title>
  </head>
  <body>
    <h1>Photos</h1>
    <div class="photo">
      <img src="photos/IMG_5115.jpg">
    </div>
    <div class="photo">
      <img src="photos/IMG_5117.jpg">
    </div>
  </body>
</html>
免责声明:我是支配者的作者
Python 是一种包含电池的语言。那么为什么不使用xml.dom.minidom呢?
from typing import List
from xml.dom.minidom import getDOMImplementation, Document
def getDOM() -> Document:
    impl = getDOMImplementation()
    dt = impl.createDocumentType(
        "html",
        "-//W3C//DTD XHTML 1.0 Strict//EN",
        "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd",
    )
    return impl.createDocument("http://www.w3.org/1999/xhtml", "html", dt)
def ul(items: List[str]) -> str:
    dom = getDOM()
    html = dom.documentElement
    ul = dom.createElement("ul")
    for item in items:
        li = dom.createElement("li")
        li.appendChild(dom.createTextNode(item))
        ul.appendChild(li)
    html.appendChild(ul)
    return dom.toxml()
if __name__ == "__main__":
    print(ul(["first item", "second item", "third item"]))
输出:
<?xml version="1.0" ?>
<!DOCTYPE html  PUBLIC '-//W3C//DTD XHTML 1.0 Strict//EN'  'http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd'>
<html>
    <ul>
        <li>first item</li>
        <li>second item</li>
        <li>third item</li>
    </ul>
</html>
该界面看起来不像 pythonic,但如果您是一名前端开发人员并使用过 JavaScript DOM 操作,那么它更符合您的想法,并且它可以让您免于添加不必要的依赖项。