Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

What is the best way to handle none in beautiful soup python

Hi I am trying to scrape and is wondering is there a one liner or simple way to handle none.
If none do something, if not none then do something else. I mean what would be the most pythonic way of handling none that references the value itself.

Right now what I have is

discount = soup.find_all('span', {"class":"jsx-30 discount"} )
if len(discount)==0:
    discount =""
else:
    discount = soup.find_all('span', {"class":"jsx-3024393758 label discount"} )[0].text 

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

In case that you only want to grab the text of the first element, I would recommend to use find() instead of find_all().

To check if element exists you can use if statement:

discount = e.text if (e := soup.find('span', {"class":"jsx-3024393758 label discount"})) else ''

or try except:

try:
    discount = soup.find('span', {"class":"jsx-3024393758 label discount"}).text
except:
    discount = ''
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading