html - 我该如何解决 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'
解决方案
它应该工作:
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 = ''
推荐阅读
- python - 最新版本的 Anaconda 抛出警告
- php - 如何从我从 PHP 中的选择下拉列表中选择的那个项目的数据库中获取文本框中的价格?
- jira - 在子任务部分显示“花费的时间”?
- python - 无法在 selenium python 中按下 javascript:void(0)
- javascript - 如何按顺序执行promise并返回所有结果
- angular - Angular 7 switchMap 调用两次
- angular - 如何使用来自另一个模块的 Angular 接口进行验证和智能感知
- codenameone - 使用 FingerprintManager 的旧 android 设备上的 NoClassDefFoundError
- python - 找到最大腹肌。每组行索引的值,排列最大值。矩阵中的对角线值,根据索引的非对角线值,找到行列式
- python - 在 Python 中加载 YAML 文件并替换结果字典中的字符串