是否可以在Google colab单元中加载JavaScript库? [英] Is it impossible to load a javascript library in a Google colab cell?

查看:99
本文介绍了是否可以在Google colab单元中加载JavaScript库?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有Python代码,该代码创建HTML,以使用 _repr_html 方法可视化Python对象.这意味着我可以通过将 display(obj)放在我的单元格中,甚至只是将 obj 作为我单元格中的最后一条语句来显示对象.

HTML从Internet加载javascript库,例如jQuery库是这样的:

 < script src =" https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"</script> 

但是,当这样的脚本标记是HTML的一部分时,我尝试在Colab中对其进行可视化,则它将被完全删除!例如,单元格中的以下代码产生的输出不再包含脚本元素:

  HTML("< div id =包含"< div id ="div1">一些文字</div>< script src =" https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"</script></div>(") 

另一种方法是在每个单元格中包含逐字逐句的javascript代码(< script type =" text/javascript> .. actual javascript ...< script> ),但似乎是不必要的开销.

有没有更优雅的解决方案?

   

解决方案

下面是一个示例:

从IPython.display中的

 导入HTML,Javascript,显示从google.colab导入输出显示(HTML(< div id ="div1">一些文字</div>(")))显示(Javascript(url ="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"))output.eval_js('''$(#div1").append("pello,JQuery/p"));'''); 

带有此示例的完整笔记本为: https://colab.research.google.com/drive/1xnfhiVsm6u_TkSoni0WaGydigOCPj5M>

I have Python code that creates HTML to visualize a Python object using the _repr_html method. This means I can show the object by simply putting display(obj) in my cell or even just placing obj as the last statement in my cell.

That HTML loads javascript libraries from the Internet, e.g. the jquery library like so:

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>

However when such a script tag is part of HTML I try to visualize in Colab, it gets completely removed! For example, the following code in a cell produces output which does not contain the script element any more:

HTML("""
<div id="containing"
<div id="div1">
  some text
</div>  
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
</div>
""")

The alternative would be to include the verbatim javascript code in every cell (<script type="text/javascript>..actual javascript ...<script>), which works, but seems like an unnecessary overhead.

Is there a more elegant solution?

解决方案

Here's an example:

from IPython.display import HTML, Javascript, display
from google.colab import output

display(HTML("""
<div id="div1">
  some text
</div>  
"""))

display(Javascript(url="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"))

output.eval_js('''
 $("#div1").append("<p>Hello, JQuery</p>");
''');

A full notebook with this example is: https://colab.research.google.com/drive/1xnfhiVsm6u_TkSoni0WaGydigOCPj5Mw

这篇关于是否可以在Google colab单元中加载JavaScript库?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆