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>
广告
© . All rights reserved.