Beautiful Soup - wrap() Method
Method Description
The wrap() method in Beautiful Soup encloses the element inside another element. You can wrap an existing tag element with another, or wrap the tag's string with a tag.
Syntax
wrap(tag)
Parameters
The tag to be wrapped with.
Return Type
The method returns a new wrapper with the given tag.
Example - Creating a new wrapper over a tag
In this example, the <b> tag is wrapped in <div> tag.
html = '''
<html>
<body>
<p>The quick, <b>brown</b> fox jumps over a lazy dog.</p>
</body>
</html>
'''
from bs4 import BeautifulSoup
soup = BeautifulSoup(html, "html.parser")
tag1 = soup.find('b')
newtag = soup.new_tag('div')
tag1.wrap(newtag)
print (soup)
Output
<html> <body> <p>The quick, <div><b>brown</b></div> fox jumps over a lazy dog.</p> </body> </html>
Example - Wrapping a String inside a tag
We wrap the string inside the <p> tag with a wrapper tag.
from bs4 import BeautifulSoup
soup = BeautifulSoup("<p>tutorialspoint.com</p>", 'html.parser')
soup.p.string.wrap(soup.new_tag("b"))
print (soup)
Output
<p><b>tutorialspoint.com</b></p>
Advertisements