Python code to consolidate CSS to HTML

We are looking for code for python that can take an HTML page and embed any related CSS style definitions used by this page into it, so there is no need to link to css pages with an external link.

You need to make separate files to insert as email attachments from existing pages used on the website. Thanks for any help.

+3
source share
3 answers

You will have to code it yourself, but BeautifulSoup will help you for a long time. Assuming all your files are local, you can do something like:

from BeautifulSoup import BeautifulSoup
soup = BeautifulSoup(open("index.html").read())
stylesheets = soup.findAll("link", {"rel": "stylesheet"})
for s in stylesheets:
    s.replaceWith('<style type="text/css" media="screen">' +
                  open(s["href"]).read()) +
                  '</style>')
open("output.html", "w").write(str(soup))

, Pythons urllib urllib2 .

+2

, . :

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))
+1

You can use pynliner . An example from their documentation:

html = "html string"
css = "css string"
p = Pynliner()
p.from_string(html).with_cssString(css)
0
source

Source: https://habr.com/ru/post/1776241/


All Articles