Beautiful Soup 简明教程

Beautiful Soup - replace_with() Method

Method Description

Beautiful Soup 的 replace_with() 方法用提供的标签或字符串替换元素中的标签或字符串。

Syntax

replace_with(tag/string)

Parameters

该方法接受一个标签对象或一个字符串作为参数。

Return Type

replace_method 不会返回新对象。

Example 1

在这个示例中,<p> 标签被使用 replace_with() 方法替换为 <b>。

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

你可以简单地通过对标签 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)

Output

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

Example 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)

Output

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