在当前的BeautifulSoup之后添加标签

nue*_*ueq 4 python beautifulsoup

我有一个循环:

for tag in soup.find('article'):
Run Code Online (Sandbox Code Playgroud)

我需要在此循环中的每个标记后添加新标记,我尝试使用insert()方法但我没有管理.

如何用BeautifulSoup解决这个任务?

Psi*_*dom 9

您可以使用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>
Run Code Online (Sandbox Code Playgroud)