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?
To insert an element after an existing element in the DOM tree, you follow these steps: First, select the parent node of the existing element. Then, insert the new element before (insertBefore()) the next sibling (nextSibling) of the existing element.
To insert element in document after div element using JavaScript, get reference to the div element; call after() method on this div element; and pass the element to insert, as argument to after() method.
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>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With