Beautiful Soup 简明教程
Beautiful Soup - wrap() Method
Method Description
Beautiful Soup 中的 wrap() 方法将元素括在另一个元素内部。你可以用另一个元素包裹现有的标签元素,或者用标签包裹标签的字符串。
The wrap() method in Beautiful Soup encloses the element inside another element. You can wrap an existing tag element with another, or wrap the tag’s string with a tag.
Example 1
在这个例子中, <b> 标签被包装在 <div> 标签中。
In this example, the <b> tag is wrapped in <div> 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('b')
newtag = soup.new_tag('div')
tag1.wrap(newtag)
print (soup)
Output
<html>
<body>
<p>The quick, <div><b>brown</b></div> fox jumps over a lazy dog.</p>
</body>
</html>