Beautiful Soup - replace_with() 方法



方法描述

Beautiful Soup 的 replace_with() 方法用提供的標籤或字串替換元素中的標籤或字串。

語法

replace_with(tag/string)

引數

該方法接受標籤物件或字串作為引數。

返回型別

replace_method 不返回新物件。

示例 1

在這個例子中,<p> 標籤被 <b> 標籤替換,使用了 replace_with() 方法。

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)

輸出

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

示例 2

您可以透過對 tag.string 物件呼叫 replace_with() 方法,簡單地用另一個字串替換標籤的內部文字。

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)

輸出

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

示例 3

用於替換的標籤物件可以透過任何 find() 方法獲得。在這裡,我們替換 <p> 標籤旁邊的標籤的文字。

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)

輸出

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