Chris
Chris

Reputation: 767

python - html- inserting sibling element containing nested tags

How to insert a sibling element containing nested tags ?

I am trying to use the insert_before function but this seems to work only for single tag. For example, having

<html>
  <body>
    <div class= first_class>
    <h1 id=Heder1>Header1</h1>
    </div>
  </body>
</html>

I try to insert above each <div class= first_class>

 <button class="accordion">
  <div class="preface">
    <i>Text</i>
  </div>
  </button>

I try to use below logic, but it doesn't work as expected. The section is not being inserted.

section_code = BeautifulSoup('<button class="accordion"><div class="preface"><i>Text</i></div></button>', 'lxml')

section = section.html.body.contents[0]

titels = soup.find_all("h1")

for title in titels:
    title.parent.insert_before(section)

How can this be achieved?

Desired output

<html>
  <body>
    <button class="accordion">
      <div class="preface">
        <i>Text</i>
      </div>
    </button>
    <div class= first_class>
    <h1 id=Heder1>Header1</h1>
    </div>
  </body>
</html>

Upvotes: 0

Views: 614

Answers (1)

KC.
KC.

Reputation: 3107

You just need to do a bit more. If you insert as str instead of bs4.element.Tag. The string will be html encode

from bs4 import BeautifulSoup

html = """
<html>
  <body>
    <div class= first_class>
    <h1 id=Heder1>Header1</h1>
    </div>
  </body>
</html>

"""

insert = """

<button class="accordion"><div class="preface"><i>Text</i></div></button>
"""
insert_content = BeautifulSoup(insert,"lxml")
soup = BeautifulSoup(html,"lxml")

title = soup.find("div")

title.insert_before(insert_content.find("button"))
print(soup.prettify())

Output

<html>
 <body>
  <button class="accordion">
   <div class="preface">
    <i>
     Text
    </i>
   </div>
  </button>
  <div class="first_class">
   <h1 id="Heder1">
    Header1
   </h1>
  </div>
 </body>
</html>

Upvotes: 1

Related Questions