Beautiful Soup, get_text but NOT the <span> text.. How can i get it?

Viewed 376

Given this markup: [MARKUP][1]

I need to get the number 182 in a column and the 58 in another. I already have the span, but when I call the div.get_tex() or string it returns = 18258(both numbers)

This is my code_:

prices= soup.find_all('div', class_='grilla-producto-precio')

cents= []
price= []
for px in prices:
    ### here i need to get the number 182 and append it to "price"
    for spn in px.find('span'):
        cents.append(spn)

HOW CAN I GET THE PRICE 182 ALONE WITHOUT THE SPAN? THANKS!!!! [1]: https://i.stack.imgur.com/ld9qo.png

2 Answers

The answer to your question is almost the same as the answer to this question.

from bs4 import BeautifulSoup

html = """
<div class = "grilla-producto-precio">
" $"
"182"
<span>58</span>
</div>
"""
soup = BeautifulSoup(html,'html5lib')

prices = soup.find_all('div',class_ = "grilla-producto-precio")

cents = []

for px in prices:
    txt = px.find_next(text=True).strip()

    txt = txt.replace('"','')

    txt = int(txt.split("\n")[-1])
    
    cents.append(txt)

Output:

[182]

Another solution is to check if the string isdigit():

from bs4 import BeautifulSoup

txt = """
<div class = "grilla-producto-precio">
" $"
"182"
<span>58</span>
</div>
"""
soup = BeautifulSoup(txt, "html.parser")

data = soup.find("div", class_="grilla-producto-precio").next
price = [int("".join(d for d in data if d.isdigit()))]

print(price) # Output: [182]
Related