代码之家  ›  专栏  ›  技术社区  ›  Recursion

在python中创建HTML

  •  34
  • Recursion  · 技术社区  · 15 年前

    我正在寻找一种在Python中动态创建HTML文件的方法。我正在编写一个库脚本,它遍历目录,收集文件元数据。我打算用这些数据自动创建一个基于HTML的图片库。一些非常简单的东西,只是一张图片表。

    我真的不认为手动写入文件是最好的方法,而且代码可能很长。那么,有没有更好的方法可以做到这一点,可能是特定于HTML的?

    4 回复  |  直到 15 年前
        1
  •  11
  •   Prof. Falken    7 年前
        2
  •  34
  •   Knio    11 年前

    Dominate

    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>
    

        3
  •  11
  •   Ignacio Vazquez-Abrams    15 年前
        4
  •  1
  •   Alex Martelli    15 年前