首页 > 解决方案 > 我该如何解决 AttributeError: 'NoneType' object has no attribute 'text' 这个问题?

问题描述

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'

标签: htmlpython-3.xweb-scrapingbeautifulsoup

解决方案


它应该工作:

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

推荐阅读