用于将CSS合并到HTML中的Python代码
问题描述:
寻找可以接受HTML页面并将该页面使用的任何链接CSS样式定义插入到其中的Python代码 - 因此不需要任何外部引用的css页面。用于将CSS合并到HTML中的Python代码
需要使单个文件作为电子邮件附件从网站上使用的现有页面插入。谢谢你的帮助。
答
你将不得不自己编码,但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))
如果文件不是本地的,你可以使用蟒蛇urllib
或urllib2
对它们进行检索。
答
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))
答
您可以使用pynliner。从他们的文档中获取示例:
html = "html string"
css = "css string"
p = Pynliner()
p.from_string(html).with_cssString(css)
您可以轻松地将CSS拉出,但是您将使用什么CSS路径来标识每个CSS片段?我不确定您可以轻松地以编程方式执行此操作。 – hughdbrown 2010-11-22 15:23:19
dup? http://*.com/questions/781382/css-parser-xhtml-generator-advice-needed – khachik 2010-11-22 15:50:52