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

时间:2017-02-07 12:26:07

标签: python beautifulsoup 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>'

1 个答案:

答案 0 :(得分:1)

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>
相关问题