将CSS合并到HTML中的Python代码

5 投票
3 回答
7952 浏览
提问于 2025-04-16 07:27

我在找一种Python代码,可以把一个HTML页面里的所有链接的CSS样式定义都插入到这个页面里。也就是说,不需要外部引用的CSS文件。

这样做是为了把现有网站上的页面做成单个文件,方便作为电子邮件附件发送。谢谢大家的帮助。

3 个回答

2

你可以使用 pynliner 这个工具。下面是他们文档中的一个例子:

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

你需要自己写代码,不过BeautifulSoup会对你有很大帮助。假设你所有的文件都在本地,你可以这样做:

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

如果文件不在本地,你可以使用Python的urlliburllib2来获取它们。

4

Sven的回答对我有帮助,但一开始并没有直接奏效。以下的内容解决了我的问题:

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

撰写回答