This HTML class allows us to save images and write texts into a single HTML file. It consists of functions such as (add a text header to the HTML file), (add a row of images to the HTML file), and (save the HTML to the disk). It is based on Python lib
| 4 | |
| 5 | |
| 6 | class HTML: |
| 7 | """This HTML class allows us to save images and write texts into a single HTML file. |
| 8 | |
| 9 | It consists of functions such as <add_header> (add a text header to the HTML file), |
| 10 | <add_images> (add a row of images to the HTML file), and <save> (save the HTML to the disk). |
| 11 | It is based on Python library 'dominate', a Python library for creating and manipulating HTML documents using a DOM API. |
| 12 | """ |
| 13 | |
| 14 | def __init__(self, web_dir, title, refresh=0): |
| 15 | """Initialize the HTML classes |
| 16 | |
| 17 | Parameters: |
| 18 | web_dir (str) -- a directory that stores the webpage. HTML file will be created at <web_dir>/index.html; images will be saved at <web_dir/images/ |
| 19 | title (str) -- the webpage name |
| 20 | refresh (int) -- how often the website refresh itself; if 0; no refreshing |
| 21 | """ |
| 22 | self.title = title |
| 23 | self.web_dir = web_dir |
| 24 | self.img_dir = os.path.join(self.web_dir, 'images') |
| 25 | if not os.path.exists(self.web_dir): |
| 26 | os.makedirs(self.web_dir) |
| 27 | if not os.path.exists(self.img_dir): |
| 28 | os.makedirs(self.img_dir) |
| 29 | |
| 30 | self.doc = dominate.document(title=title) |
| 31 | if refresh > 0: |
| 32 | with self.doc.head: |
| 33 | meta(http_equiv="refresh", content=str(refresh)) |
| 34 | |
| 35 | def get_image_dir(self): |
| 36 | """Return the directory that stores images""" |
| 37 | return self.img_dir |
| 38 | |
| 39 | def add_header(self, text): |
| 40 | """Insert a header to the HTML file |
| 41 | |
| 42 | Parameters: |
| 43 | text (str) -- the header text |
| 44 | """ |
| 45 | with self.doc: |
| 46 | h3(text) |
| 47 | |
| 48 | def add_images(self, ims, txts, links, width=400): |
| 49 | """add images to the HTML file |
| 50 | |
| 51 | Parameters: |
| 52 | ims (str list) -- a list of image paths |
| 53 | txts (str list) -- a list of image names shown on the website |
| 54 | links (str list) -- a list of hyperref links; when you click an image, it will redirect you to a new page |
| 55 | """ |
| 56 | self.t = table(border=1, style="table-layout: fixed;") # Insert a table |
| 57 | self.doc.add(self.t) |
| 58 | with self.t: |
| 59 | with tr(): |
| 60 | for im, txt, link in zip(ims, txts, links): |
| 61 | with td(style="word-wrap: break-word;", halign="center", valign="top"): |
| 62 | with p(): |
| 63 | with a(href=os.path.join('images', link)): |