如何将 HTML 嵌入到 IPython 输出中?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/25698448/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to embed HTML into IPython output?
提问by Anton Tarasenko
Is it possible to embed rendered HTML output into IPython output?
是否可以将渲染的 HTML 输出嵌入到 IPython 输出中?
One way is to use
一种方法是使用
from IPython.core.display import HTML
HTML('<a href="http://example.com">link</a>')
or (IPython multiline cell alias)
或(IPython 多行单元别名)
%%html
<a href="http://example.com">link</a>
Which return a formatted link, but
返回一个格式化的链接,但是
- This link doesn't open a browser with the webpage itself from the console. IPython notebooks support honest rendering, though.
- I'm unaware of how to render
HTML()object within, say, a list orpandasprinted table. You can dodf.to_html(), but without making links inside cells. - This output isn't interactive in the PyCharm Python console (because it's not QT).
- 此链接不会从控制台打开带有网页本身的浏览器。不过,IPython 笔记本支持诚实渲染。
- 我不知道如何
HTML()在列表或pandas打印表格中渲染对象。您可以这样做df.to_html(),但不能在单元格内建立链接。 - 此输出在 PyCharm Python 控制台中不是交互式的(因为它不是 QT)。
How can I overcome these shortcomings and make IPython output a bit more interactive?
如何克服这些缺点并使 IPython 输出更具交互性?
回答by Harmon
This seems to work for me:
这似乎对我有用:
from IPython.core.display import display, HTML
display(HTML('<h1>Hello, world!</h1>'))
The trick is to wrap it in "display" as well.
诀窍是将它也包装在“显示”中。
来源:http: //python.6.x6.nabble.com/Printing-HTML-within-IPython-Notebook-IPython-specific-prettyprint-tp5016624p5016631.html
回答by Joseph True
Expanding on @Harmon above, looks like you can combine the displayand printstatements together ... if you need. Or, maybe it's easier to just format your entire HTML as one string and then use display. Either way, nice feature.
扩展上面的@Harmon,看起来您可以将display和print语句组合在一起......如果需要的话。或者,将整个 HTML 格式化为一个字符串然后使用 display 可能更容易。无论哪种方式,不错的功能。
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>'))
Outputs something like this:
输出如下:
Hello, world!
你好,世界!
Here's a link:
这是一个链接:
some more printed text ...
一些更多的印刷文字...
Paragraph text here ...
段落文字在这里...
回答by Udi
Related: While constructing a class, def _repr_html_(self): ...can be used to create a custom HTML representation of its instances:
相关:在构造类时,def _repr_html_(self): ...可用于创建其实例的自定义 HTML 表示:
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.
有关更多信息,请参阅IPython 的文档。
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
- ? 买牛奶
- ? 做作业
- ? 玩电子游戏
回答by duhaime
Some time ago Jupyter Notebooks started stripping JavaScript from HTML content [#3118]. Here are two solutions:
不久前,Jupyter Notebooks 开始从 HTML 内容中剥离 JavaScript [ #3118]。这里有两个解决方案:
Serving Local HTML
服务本地 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:
如果你现在想在你的页面上嵌入一个带有 JavaScript 的 HTML 页面,最简单的做法是将你的 HTML 文件保存到你的笔记本所在的目录中,然后按如下方式加载 HTML:
from IPython.display import IFrame
IFrame(src='./nice.html', width=700, height=600)
Serving Remote HTML
提供远程 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 bucketso as to make the bucket host a static website, then use an Iframe component in your notebook:
如果您更喜欢托管解决方案,您可以将您的 HTML 页面上传到 S3 中的 Amazon Web Services “存储桶”,更改该存储桶上的设置以使该存储桶托管静态网站,然后在您的笔记本中使用 Iframe 组件:
from IPython.display import IFrame
IFrame(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 中呈现您的 HTML 内容和 JavaScript,就像您可以在任何其他网页上一样:
<iframe src='https://s3.amazonaws.com/duhaime/blog/visualizations/isolation-forests.html', width=700, height=600></iframe>

