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 添加在标识的标签之后。

我从尝试字符串操作开始:

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

但我相信这不是最好的课程。

谢谢你的帮助。刚开始使用 bs/bs4 但似乎无法破解。

4

1 回答 1

24

这个怎么样:

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)
于 2012-04-17T13:54:33.050 回答