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>
廣告