Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Creating HTML in python

Tags:

python

html

I am looking for a way to create html files dynamically in python. I am writing a gallery script, which iterates over directories, collecting file meta data. I intended to then use this data to automatically create a picture gallery, based on html. Something very simple, just a table of pictures.

I really don't think writing to a file manually is the best method, and the code may be very long. So is there a better way to do this, possibly html specific?

like image 378
Recursion Avatar asked Feb 20 '10 05:02

Recursion


People also ask

Can Python create HTML?

This lesson uses Python to create and view an HTML file. If you write programs that output HTML, you can use any browser to look at your results.


2 Answers

Dominate is a Python library for creating HTML documents and fragments directly in code without using templating. You could create a simple image gallery with something like this:

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()) 

Output:

<!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> 

Disclaimer: I am the author of dominate

like image 170
Knio Avatar answered Sep 29 '22 01:09

Knio


I think, if i understand you correctly, you can see here, "Templating in Python".

like image 40
ghostdog74 Avatar answered Sep 29 '22 01:09

ghostdog74