2009-10-16 46 views
4

我正在尋找一種方法來替換所有不使用正則表達式的IMG標記中的SRC屬性。 (想用任何亂的附帶默認的Python框HTML解析器安裝),我需要減少它可能是什麼都來源:使用解析器替換所有IMG元素的SRC

<img src="cid:imagename"> 

我試圖取代所有SRC標籤指向HTML電子郵件附件的cid,所以我還需要更改源文件的所有內容,所以它只是沒有路徑或擴展名的文件名。

+1

我給你推薦這個LXML,但因爲你明確地說,它必須被包括在Python,這是一個評論,不是答案。 ;) – 2009-10-16 18:58:00

+0

謝謝。我不會排除其他解決方案,並欣賞這一建議! – CPCase 2009-10-19 20:03:11

回答

18

Python標準庫中有一個HTML解析器,但它不是非常有用,它自Python 2.6以來已被棄用。用BeautifulSoup做這種事情真的很容易:

from BeautifulSoup import BeautifulSoup 
from os.path import basename, splitext 
soup = BeautifulSoup(my_html_string) 
for img in soup.findAll('img'): 
    img['src'] = 'cid:' + splitext(basename(img['src']))[0] 
my_html_string = str(soup) 
+0

感謝這個例子。我非常感謝! – CPCase 2009-10-19 20:03:46

+2

stdlib中的HTMLParser不被棄用?這是從哪裏來的?這裏是來自python 3版本的文檔:http://docs.python.org/3/library/html.parser.html – simon 2013-09-15 02:15:09

1

這是一個pyparsing方法來解決你的問題。您需要執行自己的代碼來轉換http src屬性。

from pyparsing import * 
import urllib2 

imgtag = makeHTMLTags("img")[0] 

page = urllib2.urlopen("http://www.yahoo.com") 
html = page.read() 
page.close() 

# print html 

def modifySrcRef(tokens): 
    ret = "<img" 
    for k,i in tokens.items(): 
     if k in ("startImg","empty"): continue 
     if k.lower() == "src": 
      # or do whatever with this 
      i = i.upper() 
     ret += ' %s="%s"' % (k,i) 
    return ret + " />" 

imgtag.setParseAction(modifySrcRef) 

print imgtag.transformString(html) 

代碼轉化爲:

<img src="HTTP://L.YIMG.COM/A/I/WW/BETA/Y3.GIF" title="Yahoo" height="44" width="232" alt="Yahoo!" /> 
<a href="r/xy"><img src="HTTP://L.YIMG.COM/A/I/WW/TBL/ALLYS.GIF" height="20" width="138" alt="All Yahoo! Services" border="0" /></a> 
+0

非常感謝。我會試試看。我感謝你的時間和幫助! – CPCase 2009-10-19 20:02:38