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.

Syntax

wrap(tag)

Parameters

要包装的标签。

The tag to be wrapped with.

Return Type

该方法返回一个带有给定标签的新包装器。

The method returns a new wrapper with the given 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>

Example 2

我们用一个包装器标签将 <p> 标签中的字符串包装起来。

We wrap the string inside the <p> tag with a wrapper tag.

from bs4 import BeautifulSoup

soup = BeautifulSoup("<p>tutorialspoint.com</p>", 'html.parser')
soup.p.string.wrap(soup.new_tag("b"))

print (soup)

Output

<p><b>tutorialspoint.com</b></p>