如何解决属性错误:"NoneType"对象没有此问题的属性"文本"?


nodiscount_price = container.find("div",{"class":"discount_block tab_item_discount no_discount"})
if(nodiscount_price != None):
nodiscount_price = nodiscount_price.text

nodiscount_price是一个变量,它可能有也可能没有值,这就是为什么我使用if()语句来防止任何错误,但在执行时,它会给出一个错误:

AttributeError: 'NoneType' object has no attribute 'text'

应该可以:

if nodiscount_price is not None:
nodiscount_price = nodiscount_price.text
else:
nodiscount = 'empty'

但是您也可以处理它,例如使用try & except来避免引发错误:

try:
nodiscount_price = container.find("div",{"class":"discount_block tab_item_discount no_discount"}).get_text()
except:
nodiscount_price = ''

最新更新