2012-04-16 104 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