在当前标记之后添加新的HTML标记

问题描述 投票:3回答:1

我有一个循环:

for tag in soup.find('article'):

我需要在此循环中的每个标记后添加一个新标记。我试图使用insert()方法无济于事。

如何使用BeautifulSoup解决此任务?

python beautifulsoup
1个回答
7
投票

您可以使用insert_after,如果您尝试迭代节点集,也可能需要find_all而不是find

from bs4 import BeautifulSoup
soup = BeautifulSoup("""<article>1</article><article>2</article><article>3</article>""")

for article in soup.find_all('article'):

    # create a new tag
    new_tag = soup.new_tag("tagname")
    new_tag.append("some text here")

    # insert the new tag after the current tag
    article.insert_after(new_tag)

soup

<html>
    <body>
        <article>1</article>
        <tagname>some text here</tagname>
        <article>2</article>
        <tagname>some text here</tagname>
        <article>3</article>
        <tagname>some text here</tagname>
    </body>
</html>
© www.soinside.com 2019 - 2024. All rights reserved.