user3919096
user3919096

Reputation: 71

How to add elements to beautiful soup element

if I have such bs4 element its called tab_window_uls[1]:

<ul>
<li><b>Cut:</b> Sits low on the waist.</li>
<li><b>Fit:</b> Skinny through the leg.</li>
<li><b>Leg opening:</b> Skinny.</li>
</ul>

How can I add new <li> to <ul>?

Currently my code looks like:

lines = ['a', 'b']

li_tag = tab_window_uls[1].new_tag('li')
for i in lines:
    li_tag.string = i
    tab_window_uls[1].b.string.insert_before(li_tag)

Upvotes: 2

Views: 2282

Answers (1)

heinst
heinst

Reputation: 8786

You have to create a new tag like I did and insert that tag within the ul. I load the soup, create a tag. append that tag within the other tag. (the <b> tag within the <li> tag). then load the ul tags. And insert the newly created li tag into the tree at position whatever. NOTE: you can't have it at the end, if you want it to be the last li in the list, use append.

from bs4 import BeautifulSoup

htmlText = '''
<ul>
<li><b>Cut:</b> Sits low on the waist.</li>
<li><b>Fit:</b> Skinny through the leg.</li>
<li><b>Leg opening:</b> Skinny.</li>
</ul>
'''
bs = BeautifulSoup(htmlText)

li_new_tag = bs.new_tag('li')
li_new_tag.string = 'Size:'
b_new_tag = bs.new_tag('b')
b_new_tag.string = '0 through 12.'
li_new_tag.append(b_new_tag)

tags = bs.ul
tags.insert(1, li_new_tag)
print bs.prettify()

Upvotes: 2

Related Questions