Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Stuff JS and CSS into an HTML file
"""Fetch JS & CSS referenced from the web, and stuff it into the HTML."""
import lxml.html
import requests
IN_FILE = "Using Nbconvert.slides.html"
OUT_FILE = "Using Nbconvert.slides.stuffed.html"
document = lxml.html.parse(IN_FILE)
# Stuff <script> tags
for node in document.findall(".//script[@src]"):
if node.text:
raise ValueError("Node <script src=%r> has both src and text. Can't stuff!")
src = node.attrib['src']
print("Stuffing JS:", src)
r = requests.get(src)
r.raise_for_status()
del node.attrib['src']
node.text = r.text
for node in document.findall(".//link[@rel='stylesheet']"):
if node.text:
raise ValueError("<link> element had unexpected text")
href = node.attrib['href']
if not href.startswith(('http://', 'https://', '//')):
print("Skipping local CSS URL:", href)
continue
print("Stuffing CSS:", href)
r = requests.get(href)
r.raise_for_status()
node.clear()
node.tag = 'style'
node.text = r.text
document.write(OUT_FILE, encoding='utf-8', method='html', pretty_print=True)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.