How to embed HTML into IPython output?
This seems to work for me:
from IPython.core.display import display, HTMLdisplay(HTML('<h1>Hello, world!</h1>'))
The trick is to wrap it in "display" as well.
Some time ago Jupyter Notebooks started stripping JavaScript from HTML content [#3118]. Here are two solutions:
Serving Local HTML
If you want to embed an HTML page with JavaScript on your page now, the easiest thing to do is to save your HTML file to the directory with your notebook and then load the HTML as follows:
from IPython.display import IFrameIFrame(src='./nice.html', width=700, height=600)
Serving Remote HTML
If you prefer a hosted solution, you can upload your HTML page to an Amazon Web Services "bucket" in S3, change the settings on that bucket so as to make the bucket host a static website, then use an Iframe component in your notebook:
from IPython.display import IFrameIFrame(src='https://s3.amazonaws.com/duhaime/blog/visualizations/isolation-forests.html', width=700, height=600)
This will render your HTML content and JavaScript in an iframe, just like you can on any other web page:
<iframe src='https://s3.amazonaws.com/duhaime/blog/visualizations/isolation-forests.html', width=700, height=600></iframe>
Related: While constructing a class, def _repr_html_(self): ...
can be used to create a custom HTML representation of its instances:
class Foo: def _repr_html_(self): return "Hello <b>World</b>!"o = Foo()o
will render as:
Hello World!
For more info refer to IPython's docs.
An advanced example:
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
Will render:
- ☐ Buy milk
- ☐ Do homework
- ☑ Play video games