我想使用 bs4 的 insert_after() 函数,但我不明白为什么在这种情况下它只在第二个标签之后插入 ?为什么不在每个之后呢?如果我更改代码以插入例如一些文本而不是标签,它会在每个链接之后插入它。
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 标签
插入多个地方。这里发生的是,它首先在第一个链接之后插入标签,然后,在下一次迭代中,它基本上将相同的 b
标签移动到当前链接之后。
为循环中找到的每个链接创建新标签:
for link_tag in soup.findAll('a'):
link_tag.insert_after(soup.new_tag('b'))
关于python - BeautifulSoup4 的 Insert_after() 函数意外工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28026931/