在 bs4 中将找到的标签包装在新标签内

Wrap found tag inside new tag in bs4

如何在 bs4 中用新标签包装标签。

例如我有 html 这样的。

<html>
<body>
<p>Demo</p>
<p>world</p>
</body>
</html>

我想把它转换成这个。

<html>
<body>
<b><p>Demo</p></b>
<b> <p>world</p> </b>
</body>
</html>

这里是示例。

from bs4 import BeautifulSoup
html = """
        <html>
        <body>
        <p>Demo</p>
        <p>world</p>
        </body>
        </html>"""

soup = BeautifulSoup(html, 'html.parser')

for tag in soup.find_all('p'):
#    wrap tag with '<b>'

Document:

from bs4 import BeautifulSoup
html = """
        <html>
        <body>
        <p>Demo</p>
        <p>world</p>
        </body>
        </html>"""

soup = BeautifulSoup(html, 'html.parser')
for p in soup('p'):  # shortcut for soup.find_all('p')
    p.wrap(soup.new_tag("b"))

输出:

<html>
<body>
<b><p>Demo</p></b>
<b><p>world</p></b>
</body>
</html>