Home > Mobile >  Python and Beautiful Soup nested values
Python and Beautiful Soup nested values

Time:11-24

I have the following html: <label for="prod_1234_rMon_3"> <span>12 M <span> 300 €</span></span> </label>

How can I get the 12 M and 300 €?

Thanks, Sven

Getting 12 M and 300

CodePudding user response:

You can use .get_text() with separator= and then str.split:

from bs4 import BeautifulSoup


html_doc = """\
<label  for="prod_1234_rMon_3"> <span>12 M <span> 300 €</span></span> </label>"""

soup = BeautifulSoup(html_doc, "html.parser")

a, b = soup.find("span").get_text(strip=True, separator="|").split("|")
print(a)
print(b)

Prints:

12 M
 300 €

Or: use .find and .find_next:

a = soup.find("span").find(text=True)
b = a.find_next(text=True)
print(a)
print(b)

Prints:

12 M 
 300 €
  • Related