none 美汤 python 最好的处理方法是什么

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

你好,我正在尝试抓取,想知道是否有一种单一的或简单的方法来处理 none。 如果 none 做某事,如果不 none 则做其他事情。我的意思是什么是处理引用值本身的 none 的最 pythonic 方式。

现在我有的是

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 

如果你只想抓取第一个元素的文本,我建议使用 find() 而不是 find_all()

要检查元素是否存在,您可以使用 if 语句:

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

或尝试除外:

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