Skip to content Skip to sidebar Skip to footer

How To Move Sub-tags To Right After A Mother Tag In Case There Are More Than 1 Occurrence?

I'm trying to move all sub-tags of each
to right before the its mother tag
. For example, from bs4 import BeautifulSoup txt = ''' &l

Solution 1:

This script will move all tags with class="ex_example" in front of parent <div class="c-w">:

from bs4 import BeautifulSoup

txt = '''
<divclass="c-w"><divclass="c-s"><divclass="ex_example"> aa </div><divclass="ex_example"> aa </div><divclass="ex_example"> cc </div></div></div><divclass="audio">link</div><divclass="c-w"><divclass="c-s"><divclass="ex_example"> xx </div><divclass="ex_example"> yy </div><divclass="ex_example"> zz </div></div></div>
'''

soup = BeautifulSoup(txt, 'html.parser')

for c_s in soup.select('div.c-s'):
    for c in list(c_s.contents):
        c.find_parent('div', class_='c-w').insert_before(c)

print(soup)

Prints:

<divclass="ex_example"> aa </div><divclass="ex_example"> aa </div><divclass="ex_example"> cc </div><divclass="c-w"><divclass="c-s"></div></div><divclass="audio">link</div><divclass="ex_example"> xx </div><divclass="ex_example"> yy </div><divclass="ex_example"> zz </div><divclass="c-w"><divclass="c-s"></div></div>

Post a Comment for "How To Move Sub-tags To Right After A Mother Tag In Case There Are More Than 1 Occurrence?"