如何嵌入 HTML 到 iPython notebook的输出

原创
2019/03/19 06:34
阅读数 3.2K

如何嵌入 HTML 到 iPython notebook的输出

iPython notebook中可以嵌入 HTML,也适用于JupyterHub和JupyterLab环境。不仅可以显示常用的HTML标签文本,甚至可以嵌入脚本交互操作和Frame分隔框架。具体实现可以有多种方法,效果如下。

 

%%html
<a href="http://example.com">link</a>

<a href="http://example.com">link</a>

from IPython.core.display import HTML
HTML('<a href="http://example.com">link to example.com</a>')

<a href="http://example.com">link to example.com</a>

display(HTML('<h1>Hello, world!</h1>'))
print("Here's a link:")
display(HTML("<a href='http://www.google.com' target='_blank'>www.google.com</a>"))
print("some more printed text ...")
display(HTML('<p>Paragraph text here ...</p>'))

<h1>Hello, world!</h1>

Here's a link:

<a href='http://www.google.com' target='_blank'>www.google.com</a>

some more printed text ...

<p>Paragraph text here ...</p>

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 "<ol>{}</ol>".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

<ol><li>☐ Buy milk</li><li>☐ Do homework</li><li>☑ Play video games</li></ol>

from IPython.display import IFrame

IFrame(src='https://s3.amazonaws.com/duhaime/blog/visualizations/isolation-forests.html', width=800, height=700)
    <iframe
        width="800"
        height="700"
        src="https://s3.amazonaws.com/duhaime/blog/visualizations/isolation-forests.html"
        frameborder="0"
        allowfullscreen
    ></iframe>
展开阅读全文
加载中
点击引领话题📣 发布并加入讨论🔥
打赏
0 评论
0 收藏
0
分享
返回顶部
顶部