【问题标题】:Custom CSS in Jupyter notebook that works in nbviewer在 nbviewer 中工作的 Jupyter 笔记本中的自定义 CSS
【发布时间】:2017-10-15 02:08:09
【问题描述】:

我正在阅读这两个网站,它们展示了如何在 nbviewer 中发布的 IPython 笔记本中使用自定义 CSS:

http://www.aaronschlegel.com/display-custom-ipython-notebook-themes-in-nbviewer/

https://github.com/titipata/customize_ipython_notebook

我试图在 Jupyter 笔记本中做同样的事情。但是下面的代码失败了

from IPython.core.display import HTML
import urllib.request
def css():
    style = urllib.request.urlopen('some url with css').read()
    return HTML(style)
css()

URL 是this,我尝试使用示例之一中显示的相同 CSS。

但是,尝试在单元格中运行上述代码时会抛出错误“TypeError: HTML() 期望文本不是 b'\n\nhtml...” 链接的具体内容是什么!

我使用库 requests 而不是 urllib.request 使用类似的代码执行了相同的操作,我得到了相同的 typeError。

我做错了什么?我该如何解决?提前谢谢你。

【问题讨论】:

    标签: python css python-3.x jupyter-notebook


    【解决方案1】:

    问题在于urlopen().read() 方法返回的是bytes 类型的对象,而不是str。您可以在末尾添加.decode("utf-8") 以转换为str

    但是,您提到尝试使用 requests 库,因为这对于这些类型的东西要好得多,我会将您的代码转换为使用 requests,它还将响应解析为 str。当requests 具有从响应中获取文本的内置属性时,您可能尝试在requests 响应中使用.read() 方法或其他方法。

    from IPython.core.display import HTML
    import requests
    def css():
        style = requests.get('http://www.aaronschlegel.com/display-custom-ipython-notebook-themes-in-nbviewer/#viewSource').text
        return HTML(style)
    css()
    

    【讨论】:

      猜你喜欢
      • 2021-03-27
      • 1970-01-01
      • 2019-10-09
      • 2016-12-06
      • 1970-01-01
      • 1970-01-01
      • 2017-03-13
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多