html.py 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  1. import dominate
  2. from dominate.tags import *
  3. import os
  4. class HTML:
  5. def __init__(self, web_dir, title, refresh=0):
  6. self.title = title
  7. self.web_dir = web_dir
  8. self.img_dir = os.path.join(self.web_dir, 'images')
  9. if not os.path.exists(self.web_dir):
  10. os.makedirs(self.web_dir)
  11. if not os.path.exists(self.img_dir):
  12. os.makedirs(self.img_dir)
  13. self.doc = dominate.document(title=title)
  14. if refresh > 0:
  15. with self.doc.head:
  16. meta(http_equiv="refresh", content=str(refresh))
  17. def get_image_dir(self):
  18. return self.img_dir
  19. def add_header(self, str):
  20. with self.doc:
  21. h3(str)
  22. def add_table(self, border=1):
  23. self.t = table(border=border, style="table-layout: fixed;")
  24. self.doc.add(self.t)
  25. def add_images(self, ims, txts, links, width=512):
  26. self.add_table()
  27. with self.t:
  28. with tr():
  29. for im, txt, link in zip(ims, txts, links):
  30. with td(style="word-wrap: break-word;", halign="center", valign="top"):
  31. with p():
  32. with a(href=os.path.join('images', link)):
  33. img(style="width:%dpx" % (width), src=os.path.join('images', im))
  34. br()
  35. p(txt)
  36. def save(self):
  37. html_file = '%s/index.html' % self.web_dir
  38. f = open(html_file, 'wt')
  39. f.write(self.doc.render())
  40. f.close()
  41. if __name__ == '__main__':
  42. html = HTML('web/', 'test_html')
  43. html.add_header('hello world')
  44. ims = []
  45. txts = []
  46. links = []
  47. for n in range(4):
  48. ims.append('image_%d.jpg' % n)
  49. txts.append('text_%d' % n)
  50. links.append('image_%d.jpg' % n)
  51. html.add_images(ims, txts, links)
  52. html.save()