Add parent tags with beautiful soup

2020-04-16 04:36发布

问题:

I have many pages of HTML with various sections containing these code snippets:

<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>

I can parse the HTML successfully and extract these relevant tags

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

Now I need to add new parent tags about these such that the code snippet goes:

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

But I can't find a way of adding parent tags in bs4 such that they brace the identified tags. insert()/insert_before add in after the identified tags.

I started by trying string manupulation:

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

but I believe this isn't the best course.

Thanks for any help. Just started using bs/bs4 but can't seem to crack this.

回答1:

How about this:

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

Simple example:

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>

Example with your document:

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