我该如何解决 AttributeError: 'NoneType' object has no attribute 'text' 这个问题? [英] How may I solve AttributeError: 'NoneType' object has no attribute 'text' for this problem?

查看:192
本文介绍了我该如何解决 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() 语句来防止任何错误,但在执行时,它会给出错误:

nodiscount_price is a variable that may or may not have a value that is why I used an if() statement to prevent any error but when executed, it gives an error:

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

推荐答案

应该可以:

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

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

But you can also handle it for example with try & except to avoid raising an error:

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

这篇关于我该如何解决 AttributeError: 'NoneType' object has no attribute 'text' 这个问题?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆