Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python code to consolidate CSS into HTML

Tags:

python

html

css

Looking for python code that can take an HTML page and insert any linked CSS style definitions used by that page into it - so any externally referenced css page(s) are not needed.

Needed to make single files to insert as email attachments from existing pages used on web site. Thanks for any help.

like image 639
Scott Treseder Avatar asked Nov 22 '10 15:11

Scott Treseder


1 Answers

Sven's answer helped me, but it didn't work out of the box. The following did it for me:

import bs4   #BeautifulSoup 3 has been replaced
soup = bs4.BeautifulSoup(open("index.html").read())
stylesheets = soup.findAll("link", {"rel": "stylesheet"})
for s in stylesheets:
    t = soup.new_tag('style')
    c = bs4.element.NavigableString(open(s["href"]).read())
    t.insert(0,c)
    t['type'] = 'text/css'
    s.replaceWith(t)
open("output.html", "w").write(str(soup))
like image 83
Permafacture Avatar answered Oct 05 '22 22:10

Permafacture