How to embed HTML into iPython output?
是否可以将渲染的HTML输出嵌入到iPython输出中?
一种方法是使用
1 2 | from IPython.core.display import HTML HTML('link') |
或(IPython多行单元别名)
1 2 | %%html link |
哪个返回格式化的链接,但是
如何克服这些缺点,并使iPython输出更具交互性?
这似乎为我工作:
1 2 | from IPython.core.display import display, HTML display(HTML('Hello, world!')) |
诀窍是也将其包装在"显示"中。
来源:http://python.6.x6.nabble.com/Printing-HTML-within-IPython-Notebook-IPython-specific-prettyprint-tp5016624p5016631.html
一段时间之前,Jupyter Notebooks开始从HTML内容中剥离JavaScript [#3118]。这是两个解决方案:
提供本地HTML
如果要立即在页面上嵌入带有JavaScript的HTML页面,最简单的方法是使用笔记本将HTML文件保存到目录中,然后按以下方式加载HTML:
1 2 3 | from IPython.display import IFrame IFrame(src='./nice.html', width=700, height=600) |
提供远程HTML
如果您喜欢托管解决方案,则可以在S3中将HTML页面上传到Amazon Web Services"存储桶",更改该存储桶上的设置,以使存储桶托管静态网站,然后在笔记本中使用Iframe组件:
1 2 3 | from IPython.display import IFrame IFrame(src='https://s3.amazonaws.com/duhaime/blog/visualizations/isolation-forests.html', width=700, height=600) |
就像在其他任何网页上一样,这将在iframe中呈现HTML内容和JavaScript:
1 | <iframe src='https://s3.amazonaws.com/duhaime/blog/visualizations/isolation-forests.html', width=700, height=600></iframe> |
相关:在构造类时,
1 2 3 4 5 6 | class Foo: def _repr_html_(self): return"Hello World!" o = Foo() o |
将呈现为:
Hello World!
有关更多信息,请参阅IPython的文档。
一个高级示例:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 | from html import escape # Python 3 only :-) class Todo: def __init__(self): self.items = [] def add(self, text, completed): self.items.append({'text': text, 'completed': completed}) def _repr_html_(self): return"{}".format("".join(" <li> {} {} </li> ".format( "?" if item['completed'] else"?", escape(item['text']) ) for item in self.items)) my_todo = Todo() my_todo.add("Buy milk", False) my_todo.add("Do homework", False) my_todo.add("Play video games", True) my_todo |
将呈现:
? Buy milk ? Do homework ? Play video games
在上面的@Harmon上展开,看起来您可以将
1 2 3 4 5 6 7 | display(HTML('Hello, world!')) print("Here's a link:") display(HTML("www.google.com")) print("some more printed text ...") display(HTML('<p> Paragraph text here ... </p>')) |
输出如下所示:
你好,世界!
这里是一个链接:
www.google.com
一些更多的印刷文字...
此处的段落文字...