Python print the parent element without printing the child element text

Question:

I’m using beautiful soup. I want to print the text with parent element without getting printing the child element.

<li class="list-item p-a-0"><b class="inline">First Name:</b> James </li>

Expected Output:

James

this is my code:

for item in soup2.findAll('div',{'class':'box-body light-b'}):
    sub_items = item.findAll('li')
    for sub_item in sub_items:
        print(sub_item)

li and b element,

I just want to print li element without printing the b element.

Asked By: makerr

||

Answers:

there are two ways you can do it

# 1
for item in soup2.findAll("div", {"class": "box-body light-b"}):
    sub_items = item.findAll("li")
    for sub_item in sub_items:
        print(list(sub_item.strings)[-1]) # prints James
# 2
for item in soup2.findAll("div", {"class": "box-body light-b"}):
    sub_items = item.findAll("li")
    for sub_item in sub_items:
        for child in sub_item.findAll("b"):
            child.decompose() # removes the b tag
        print(sub_item.text)   

      
Answered By: Sreevardhan Reddy
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.