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

Time:03-30

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 

CodePudding user response:

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 = ''
  • Related