Insert_after() BeautifulSoup4 的函数意外工作

Insert_after() function of BeautifulSoup4 works unexpectidly

我想使用 bs4 的 insert_after() 函数,但我不明白为什么在这种情况下它只在第二个标签之后插入 ?为什么不在每个之后呢?如果我更改代码以插入例如一些文本而不是标签,它会在每个 link.

之后插入它
from bs4 import BeautifulSoup
soup = BeautifulSoup('<p><a href="http://www.foo.com">this if foo</a><a href="http://www.bar.com">this if bar</a></p>')
b = soup.new_tag('b')
for link_tag in soup.findAll('a'):
    link_tag.insert_after(b)
print soup

输出:

<html>
    <p>
      <a href="http://www.foo.com">
        this if foo
      </a>
      <a href="http://www.bar.com">
        this if bar
      </a>
      <b>
      </b>
    </p>
  </body>
</html>

能否请您向我解释一下如何使用此功能在每个标签后插入?

不要在多个地方插入 相同的 BeautifulSoup Tag。这里发生的是它首先在第一个 link 之后插入标签,然后,在下一次迭代中,它基本上在当前 link.[=13 之后移动相同的 b 标签=]

为循环中找到的每个 link 创建新标签:

for link_tag in soup.findAll('a'):
    link_tag.insert_after(soup.new_tag('b'))