Pjoern
Pjoern

Reputation: 339

How to wrap string by tag in Beautifulsoup?

I want to wrap the content of a lot of div-elements/blocks with p tags:

<div class='value'>
  some content
</div>

It should become:

<div class='value'>
  <p>
    some content
  </p>
</div>

My idea was to get the content (using bs4) by filtering strings with find_all and then wrap it with the new tag. Don't know, if its working. I cant filter content from tags with specific attributes/values.

I can do this instead of bs4 with regex. But I'd like to do all transformations (there are some more beside this one) in bs4.

Upvotes: 1

Views: 1537

Answers (1)

Bill Bell
Bill Bell

Reputation: 21643

Believe it or not, you can use wrap. :-)

Because you might, or might not, want to wrap inner div elements I decided to alter your HTML code a little bit, so that I could give you code that shows how to alter an inner div without changing the one 'outside' it. You will see how to alter all divs, I'm sure.

Here's how.

>>> from bs4 import BeautifulSoup
>>> soup = BeautifulSoup(open('pjoern.htm').read(), 'lxml')
>>> inner_div = soup.findAll('div')[1]
>>> inner_div
<div>
some content
</div>
>>> inner_div.contents[0].wrap(soup.new_tag('p'))
<p>
some content
</p>
>>> print(soup.prettify())
<html>
 <body>
  <div class="value">
   <div>
    <p>
     some content
    </p>
   </div>
  </div>
 </body>
</html>

Upvotes: 3

Related Questions