Reputation: 309
I have a loop:
for tag in soup.find('article'):
I need to add a new tag after each tag in this loop. I tried to use the insert()
method to no avail.
How can I solve this task with BeautifulSoup?
Upvotes: 8
Views: 9715
Reputation: 214957
You can use insert_after
, and also you probably need find_all
instead of find
if you are trying to iterate through the node set:
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>
Upvotes: 16