Skip to main content
 首页 » 编程设计

python之在 nbviewer 中工作的 Jupyter notebook 中的自定义 CSS

2024年10月01日7thcjp

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

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

https://github.com/titipata/customize_ipython_notebook

我正尝试在 Jupyter notebook 中做同样的事情。但是下面的代码失败了

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

网址是this ,我正在尝试使用其中一个示例中显示的相同 CSS。

然而,尝试在单元格中运行上述代码会抛出错误“TypeError: HTML() expects text not b'\n\nhtml...”链接的内容到底是什么!

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

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

请您参考如下方法:

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

但是,您提到了尝试使用 requests 库,因为这对于这些类型的事情要好得多,我会将您的代码转换为使用 requests还将响应解析为 str。当 requests 有一个内置属性来获取来自回复的文本。

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