bs4.element.NavigableString Type Conversion Method

Asked 2 years ago, Updated 2 years ago, 116 views

    url = endpoint + paramset
    result = requests.get(url)

    bs_obj = bs4.BeautifulSoup(result.content, "html.parser")

    list_dlnm = []

    for j in range(len(bs_obj.findAll("dlnm"))):
        list_dlnm.append(bs_obj.findAll("dlnm")[j]) #dlnmTagFind, Add List
        list_dlnm.append(bs_obj.findAll("vol_3")[j]) #vol_3 Find Tag, Add List 

Found the tag dlnm in the html document and saved it in the list_dlnm list.

I want to find the sum of the elements in the list, but I couldn't because of the error message below. TypeError: unsupported operand type(s) for +: 'int' and 'NavigableString'

The type of list_dlnm[0] comes out like below, is there a way to change it to str or int type?

<class 'bs4.element.NavigableString'>

python beautifulsoup

2022-09-21 17:36

1 Answers

It's a self-answer... I solved it somehow.

 for j in range (len(bs_obj.findAll("dlnm")):
        list_dlnm.append(bs_obj.findAll("dlnm")[j].get_text()) #dlnm Find Tag, Add List
        list_dlnm.append(int(bs_obj.findAll("vol_3")[j].get_text())) # vol_3 Find tags, add list


2022-09-21 17:36

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.