Beautiful Soup – replace_with Method


Beautiful Soup – replace_with() Method



”;


Method Description

Beautiful Soup”s replace_with() method replaces a tag or string in an element with the provided tag or string.

Syntax


replace_with(tag/string)

Parameters

The method accepts a tag object or a string as argument.

Return Type

The replace_method doesn”t return a new object.

Example 1

In this example, the <p> tag is replaced by <b> with the use of replace_with() method.


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

soup = BeautifulSoup(html, "html.parser")
tag1 = soup.find(''p'')
txt = tag1.string
tag2 = soup.new_tag(''b'')
tag2.string = txt
tag1.replace_with(tag2)
print (soup)

Output


<html>
<body>
<b>The quick, brown fox jumps over a lazy dog.</b>
</body>
</html>

Example 2

You can simply replace the inner text of a tag with another string by calling replace_with() method on the tag.string object.


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

soup = BeautifulSoup(html, "html.parser")
tag1 = soup.find(''p'')
tag1.string.replace_with("DJs flock by when MTV ax quiz prog.")
print (soup)

Output


<html>
<body>
<p>DJs flock by when MTV ax quiz prog.</p>
</body>
</html>

Example 3

The tag object to be used for replacement can be obtained by any of the find() methods. Here, we replace the text of the tag next to <p> 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(''p'')
tag1.find_next(''b'').string.replace_with(''black'')
print (soup)

Output


<html>
<body>
<p>The quick, <b>black</b> fox jumps over a lazy dog.</p>
</body>
</html>

Advertisements

”;

Leave a Reply

Your email address will not be published. Required fields are marked *