Beautiful Soup - unwrap() Method



Method Description

The unwrap() method is the opposite of wrap() method. It It replaces a tag with whatever's inside that tag. It removes the tag from an element and returns it.

Syntax

unwrap()

Parameters

The method doesn't require any parameter.

Return Type

The unwrap() method returns the tag that has been removed.

Example 1

In the following example, the <b> tag from the html string is removed.

html = '''
<p>The quick, <b>brown</b> fox jumps over a lazy dog.</p>
'''
from bs4 import BeautifulSoup

soup = BeautifulSoup(html, "html.parser")
tag1 = soup.find('b')
newtag = tag1.unwrap()

print (soup)

Output

<p>The quick, brown fox jumps over a lazy dog.</p>

Example 2

The code below prints the returned value of unwrap() method.

html = '''
<p>The quick, <b>brown</b> fox jumps over a lazy dog.</p>
'''
from bs4 import BeautifulSoup

soup = BeautifulSoup(html, "html.parser")
tag1 = soup.find('b')
newtag = tag1.unwrap()

print (newtag)

Output

<b></b>

Example 3

The unwrap() method is useful for good for stripping out markup, as the following code shows −

html = '''
<html>
   <body>
      <p>The quick, brown fox jumps over a lazy dog.</p>
      <p>DJs flock by when MTV ax quiz prog.</p>
      <p>Junk MTV quiz graced by fox whelps.</p>
      <p>Bawds jog, flick quartz, vex nymphs.</p>
   </body>
</html>
'''
from bs4 import BeautifulSoup

soup = BeautifulSoup(html, "html.parser")
#print (soup.unwrap())
for tag in soup.find_all():
   tag.unwrap()
print (soup)

Output

The quick, brown fox jumps over a lazy dog.
DJs flock by when MTV ax quiz prog.
Junk MTV quiz graced by fox whelps.
Bawds jog, flick quartz, vex nymphs.
Advertisements