Beautiful Soup 简明教程
Beautiful Soup - replace_with() Method
Method Description
Beautiful Soup 的 replace_with() 方法用提供的标签或字符串替换元素中的标签或字符串。
Beautiful Soup’s replace_with() method replaces a tag or string in an element with the provided tag or string.
Example 1
在这个示例中,<p> 标签被使用 replace_with() 方法替换为 <b>。
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)
Example 2
你可以简单地通过对标签 string 对象调用 replace_with() 方法,将标签的内部文本替换为另一个字符串。
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)
Example 3
可用于替换的标签对象,可通过任意 find() 方法获得。在这里,我们替换 <p> 标签旁边的标签的文本。
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)