Beautiful Soup - wrap() 方法



方法描述

Beautiful Soup 中的 wrap() 方法将元素包含在另一个元素内。您可以用另一个标签元素包装现有的标签元素,或者用标签包装标签的字符串。

语法

wrap(tag)

参数

要包装的标签。

返回类型

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

示例 1

在此示例中,<b> 标签被包装在 <div> 标签中。

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)

输出

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

示例 2

我们用包装器标签包装 <p> 标签内的字符串。

from bs4 import BeautifulSoup

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

print (soup)

输出

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

© . All rights reserved.