user4901852
user4901852

Reputation:

Custom CSS in Jupyter notebook that works in nbviewer

I was reading these two webs that show how to use custom CSS in IPython notebooks published in nbviewer:

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

https://github.com/titipata/customize_ipython_notebook

Im trying to do the same in a Jupyter notebook. However the code below fails

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

the URL is this, Im trying to use the same CSS that is shown in one of the examples.

However trying to run the above code in a cell it throw the error "TypeError: HTML() expects text not b'\n\nhtml..." what is exactly the content of the link!

I did the same operation using the library requests instead of urllib.request with a similar code and I got the same typeError.

What Im doing wrong? How I can fix it? Thank you in advance.

Upvotes: 2

Views: 794

Answers (1)

Louise Davies
Louise Davies

Reputation: 15961

The problem is that urlopen().read() method is returning a bytes type object rather than a str. You can add a .decode("utf-8") at the end to convert to str.

However, you mentioned attempting to use the requests library, and since that is so much nicer for these types of things I'll convert you code to use requests that also parses the response into a str. You probably tried to use the .read() method or something on the requests response, when requests has a built-in attribute to get the text from a response.

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

Upvotes: 1

Related Questions