2012-04-16 87 views
2

我有一個包含這些代碼片段各個部分HTML的許多網頁:添加父標籤與美麗的湯

<div class="footnote" id="footnote-1"> 
<h3>Reference:</h3> 
<table cellpadding="0" cellspacing="0" class="floater" style="margin-bottom:0;" width="100%"> 
<tr> 
<td valign="top" width="20px"> 
<a href="javascript:void(0);" onclick='javascript:toggleFootnote("footnote-1");' title="click to hide this reference">1.</a> 
</td> 
<td> 
<p> blah </p> 
</td> 
</tr> 
</table> 
</div> 

我可以成功地解析HTML和提取這些相關標籤

tags = soup.find_all(attrs={"footnote"}) 

現在我需要添加新的父標籤有關這些使得代碼段雲:

<div class="footnote-out"><CODE></div> 

但我不能找到一種在bs4中添加父標籤的方法,以便它們支持已識別的標籤。將insert()/ insert_before添加到識別的標籤後面。

,我開始試圖通過字符串manupulation:

for tags in soup.find_all(attrs={"footnote"}): 
     tags = BeautifulSoup("""<div class="footnote-out">"""+str(tags)+("</div>")) 

,但我相信這不是最好的辦法。

感謝您的任何幫助。剛開始使用bs/bs4,但似乎無法破解這一點。

回答

10

如何:

def wrap(to_wrap, wrap_in): 
    contents = to_wrap.replace_with(wrap_in) 
    wrap_in.append(contents) 

簡單的例子:

from bs4 import BeautifulSoup 
soup = BeautifulSoup("<body><a>Some text</a></body>") 
wrap(soup.a, soup.new_tag("b")) 
print soup.body 
# <body><b><a>Some text</a></b></body> 

實例與您的文檔:

for footnote in soup.find_all("div", "footnote"): 
    new_tag = soup.new_tag("div") 
    new_tag['class'] = 'footnote-out' 
    wrap(footnote, new_tag) 
+0

感謝您抽出寶貴時間來幫助我。你的解決方案工作得很好。 – Cosades 2012-04-17 14:29:17