嗨,我正在嘗試刮擦,想知道是否有一種襯里或簡單的方法來處理。如果沒有人做某事,如果沒有人做其他事情。我的意思是什么是處理任何參考值本身的最 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
uj5u.com熱心網友回復:
如果您只想獲取第一個元素的文本,我建議您使用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 = ''
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/454880.html
