2014-12-01 101 views
6

我有一個HTML文件集合。我希望一個一個地遍歷它們,編輯特定類的標記。我想編輯的代碼是以下形式,使用下面的類名稱:用BeautifulSoup中的另一個標籤替換一種標籤

<td class='thisIsMyClass' colspan=4> 
    <a id='123' class='thisIsMyOtherClass' href='123'>Put me Elsewhere</a> 

這可以在同一文檔中出現多次,用不同的文本,而不是「把我在別處」,但始終不變類。

我想改變這是下面的形式:

<font SIZE="3" COLOR="#333333" FACE="Verdana" STYLE="background-color:#ffffff;font-weight: bold;"> 
    <h2>Put Me Elsewhere</h2> 
</font> 
import os 
for filename in os.listdir('dirname'): 
replace(filename) 

def replace(filename): 
tags = soup.find_all(attrs={"thisIsMyClass"}) 

不太清楚在這之後去哪裏或如何處理標籤陣列?任何幫助將非常感激。謝謝:)

+0

HTML對

元素的兒童有一些限制。您可能只想考慮更換標籤。如果由於其屬性需要擦除​​,可能將其替換爲普通的​​會比完全刪除它們更好。 – tiffon 2014-12-07 01:57:57

回答

4

好得多,更漂亮將是一個佔位符準備替換HTML字符串,找到所有td標籤與thisIsMyClass類,並使用.replace_with()來代替每個:

from bs4 import BeautifulSoup 

data = """ 
<table> 
    <tr> 
     <td class='thisIsMyClass' colspan=4> 
      <a id='123' class='thisIsMyOtherClass' href='123'>Put me Elsewhere</a> 
     </td> 
    </tr> 
</table> 
""" 

replacement = """ 
<font SIZE="3" COLOR="#333333" FACE="Verdana" STYLE="background-color:#ffffff;font-weight: bold;"> 
    <h2>{text}</h2> 
</font> 
""" 

soup = BeautifulSoup(data, 'html.parser') 
for td in soup.select('td.thisIsMyClass'): 
    td.replace_with(BeautifulSoup(replacement.format(text=td.a.text), 'html.parser')) 

print soup.prettify() 

打印:

<table> 
    <tr> 
     <font color="#333333" face="Verdana" size="3" style="background-color:#ffffff;font-weight: bold;"> 
      <h2> 
      Put me Elsewhere 
      </h2> 
     </font> 
    </tr> 
</table> 
1

這就像分配給name屬性一樣簡單。

# for quick testing: 
# tag = BeautifulSoup("<td class='thisIsMyClass' colspan=4><a id='123' class='thisIsMyOtherClass' href='123'>Put me Elsewhere</a>") 
# tags = [tag] 
for tag in tags: 
    tag.td.name = "font" 
    tag.font["SIZE"] = 3 
    del tag.font["class"] 
    ... 
    tag.a.name = "h2" 
    ... 
    print(tag) 
    # <font SIZE="3" colspan="4"><h2 class="thisIsMyOtherClass" href="123" id="123">Put me Elsewhere</h2></font> 

另外documentation是你的朋友。這是相當全面的。

相關問題