NoneType没有属性IF-ELSE解决方案 [英] NoneType has no attribute IF-ELSE solution

查看:48
本文介绍了NoneType没有属性IF-ELSE解决方案的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在解析HTML文件,并在其中搜索订单状态.有时,状态不存在,所以当我使用它时,BeautifulSoup返回NoneType.为了解决这个问题,我使用了if-else语句,但是它也不起作用.Python返回:

I'm parsing an HTML file and searching for status of order in it. Sometimes, status doesn't exist, so BeautifulSoup returns NoneType, when I'm using it. To solve this problem I use if-else statement, but it doesn't work too. Python returns:

TypeError:类型为'NoneType'的对象没有len()

TypeError: object of type 'NoneType' has no len()

我正在为词典添加状态,该词典包含订单中的其他信息.下面的代码是一部分,它将新订单的信息添加到字典中.

I am adding status to a dictionary, which contains other info from the order. The code below is a part, which adds new order's info to a dict.

database.append({
        "Title": title[0] + title.lower()[1:],
        "Name": name[0].upper() + name[1:],
        "Status": status.string[:len(status.string)-3] if status is not None else "Not listed",
        "Price": price
    })

推荐答案

似乎有三种情况:

  1. 状态为无"
  2. 状态不是None ,但是 status.string
  3. status status.string 均为 not None
  1. status is None
  2. status is not None, but status.string is
  3. both status and status.string are not None

您必须提供处理每种情况的代码.

You have to provide code that handles each case.

if status is not None and status.string is not None:
     st = status.string[:-3]
else:
     st = "Not listed"

database.append({
        "Title": title[0] + title.lower()[1:],
        "Name": name[0].upper() + name[1:],
        "Status": st,
        "Price": price
    })

如果愿意,您还可以将整个 if 粘贴在字典中.您还可以使用例外:

You can also stick the whole if in the dict if you prefer. You could also use exceptions:

try:
     st = status.string[:-3]
except (TypeError, AttributeError):
     st = "Not listed"

这篇关于NoneType没有属性IF-ELSE解决方案的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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