如何将HTML嵌入IPython输出中?

问题:如何将HTML嵌入IPython输出中?

是否可以将呈现的HTML输出嵌入到IPython输出中?

一种方法是使用

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

或(IPython多行单元格别名)

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

哪个返回格式化的链接,但是

  1. 此链接不会从控制台打开带有网页本身的浏览器。不过,IPython笔记本支持诚实渲染。
  2. 我不知道如何HTML()在列表或pandas打印表中呈现对象。您可以这样做df.to_html(),但无需在单元格内建立链接。
  3. 此输出在PyCharm Python控制台中不是交互式的(因为它不是QT)。

如何克服这些缺点并使IPython输出更具交互性?

Is it possible to embed rendered HTML output into IPython output?

One way is to use

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

or (IPython multiline cell alias)

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

Which return a formatted link, but

  1. This link doesn’t open a browser with the webpage itself from the console. IPython notebooks support honest rendering, though.
  2. I’m unaware of how to render HTML() object within, say, a list or pandas printed table. You can do df.to_html(), but without making links inside cells.
  3. This output isn’t interactive in the PyCharm Python console (because it’s not QT).

How can I overcome these shortcomings and make IPython output a bit more interactive?


回答 0

这似乎为我工作:

from IPython.core.display import display, HTML
display(HTML('<h1>Hello, world!</h1>'))

诀窍是也将其包装在“显示”中。

来源:http : //python.6.x6.nabble.com/Printing-HTML-within-IPython-Notebook-IPython-specific-prettyprint-tp5016624p5016631.html

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.

Source: http://python.6.x6.nabble.com/Printing-HTML-within-IPython-Notebook-IPython-specific-prettyprint-tp5016624p5016631.html


回答 1

一段时间以前,Jupyter Notebooks开始从HTML内容中剥离JavaScript [ #3118 ]。这是两个解决方案:

提供本地HTML

如果要立即在页面上嵌入带有JavaScript的HTML页面,最简单的方法是使用笔记本将HTML文件保存到目录中,然后按以下方式加载HTML:

from IPython.display import IFrame

IFrame(src='./nice.html', width=700, height=600)

提供远程HTML

如果您喜欢托管解决方案,则可以在S3中将HTML页面上传到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)

就像在其他任何网页上一样,这将在iframe中呈现HTML内容和JavaScript:

<iframe src='https://s3.amazonaws.com/duhaime/blog/visualizations/isolation-forests.html', width=700, height=600></iframe>

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 IFrame

IFrame(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 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 src='https://s3.amazonaws.com/duhaime/blog/visualizations/isolation-forests.html', width=700, height=600></iframe>

回答 2

相关:在构造类时,def _repr_html_(self): ...可用于创建其实例的自定义HTML表示形式:

class Foo:
    def _repr_html_(self):
        return "Hello <b>World</b>!"

o = Foo()
o

将呈现为:

世界你好!

有关更多信息,请参阅IPython的文档

一个高级示例:

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

将呈现:

  1. ☐购买牛奶
  2. ☐做作业
  3. ☑玩电子游戏

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:

  1. ☐ Buy milk
  2. ☐ Do homework
  3. ☑ Play video games

回答 3

在上面的@Harmon上展开,看来您可以将displayand print语句组合在一起……如果需要的话。或者,将整个HTML格式化为一个字符串然后使用显示可能会更容易。无论哪种方式,不错的功能。

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>'))

输出如下所示:


你好,世界!

这里是一个链接:

www.google.com

一些更多的印刷文字…

此处的段落文字…


Expanding on @Harmon above, looks like you can combine the display and print statements 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.

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:

www.google.com

some more printed text …

Paragraph text here …