如何使用python生成静态.html

时间:2018-01-02 16:37:34

标签: python html plotly static-html

我正在寻找一个python解决方案来创建一个可以通过电子邮件发送的静态.html,无论是附加还是嵌入到电子邮件中(如果需要更多工作,请忽略后一个选项)。我没有关于.html布局的要求。这里的重点是确定生成离线.html的不那么痛苦的解决方案。

潜在的解决方案可能与以下伪代码一致。

from some_unknown_pkg import StaticHTML

# Initialise instance
newsletter = StaticHTML()

# Append charts, tables and text to blank newsletter.
newsletter.append(text_here)
newsletter.append(interactive_chart_generated_with_plotly)
newsletter.append(more_text_here)
newsletter.append(a_png_file_loaded_from_local_pc)



# Save newsletter to .html, ready to be sent out.
newsletter.save_to_html('newsletter.html')

可以在任何浏览器中打开'newsletter.html'。只是为了提供更多的上下文,这个.html应该发送给我公司内部的一些选定的人并包含合理的数据。我正在使用plotly生成要插入.html中的交互式图表。

4 个答案:

答案 0 :(得分:3)

通过导入sys模块启动您的python模块并将stdout重定向到newsletter.html

import sys
sys.stdout = open('newsletter.html','w')

这会将生成的任何输出重定向到html文件。现在,只需在python中使用print命令将html标记传输到该文件。例如,尝试:

print "<html>"
print "<p> This is my NewsLetter </p>"
print "</html>"`

此代码段将创建一个基本的HTML文件。现在,您可以在任何浏览器中打开此文件。要发送电子邮件,您可以使用python的emailsmtplib模块。

答案 1 :(得分:2)

可能的解决方案here

看来那个答案正是你想要的。文档:http://www.yattag.org/

另一个非常好的包here

答案 2 :(得分:1)

我遇到了完全相同的问题,找不到简单的Python包,所以我创建了自己的:

https://github.com/ar-nowaczynski/htmlcreator

对于python> = 3.6:

pip install htmlcreator

示例:

from htmlcreator import HTMLDocument

document = HTMLDocument()

document.set_title('my title')
document.add_header('section 1')
document.add_text('my text')
document.add_header('section 2')
document.add_image('/path/to/image.jpg')  # images are fully embedded inside

document.write('my_document.html')  # standalone file

此处的完整示例:https://github.com/ar-nowaczynski/htmlcreator/blob/master/examples/1_build_first_document.py

文件预览示例:https://htmlpreview.github.io/?https://github.com/ar-nowaczynski/htmlcreator/blob/master/examples/1_first_document.html

答案 3 :(得分:0)

Dominate软件包看起来像它提供了一种简单直观的方法来创建HTML页面。 https://www.yattag.org/