2010-11-22 72 views
3

尋找可以接受HTML頁面並將該頁面使用的任何鏈接CSS樣式定義插入到其中的Python代碼 - 因此不需要任何外部引用的css頁面。用於將CSS合併到HTML中的Python代碼

需要使單個文件作爲電子郵件附件從網站上使用的現有頁面插入。謝謝你的幫助。

+0

您可以輕鬆地將CSS拉出,但是您將使用什麼CSS路徑來標識每個CSS片段?我不確定您可以輕鬆地以編程方式執行此操作。 – hughdbrown 2010-11-22 15:23:19

+0

dup? http://stackoverflow.com/questions/781382/css-parser-xhtml-generator-advice-needed – khachik 2010-11-22 15:50:52

回答

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

如果文件不是本地的,你可以使用蟒蛇urlliburllib2對它們進行檢索。

1

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

您可以使用pynliner。從他們的文檔中獲取示例:

html = "html string" 
css = "css string" 
p = Pynliner() 
p.from_string(html).with_cssString(css) 
相關問題