Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add new HTML tag after current tag

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?

like image 675
nueq Avatar asked May 28 '17 21:05

nueq


People also ask

How do you add an element to an existing element?

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.

How do I append a div after another div?

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.


1 Answers

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>
like image 62
Psidom Avatar answered Oct 22 '22 15:10

Psidom