NoneType没有属性IF-ELSE解决方案 [英] NoneType has no attribute IF-ELSE solution
问题描述
我正在解析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
})
推荐答案
似乎有三种情况:
-
状态
为无" -
状态不是None
,但是status.string
是 -
status
和status.string
均为not None
status
is Nonestatus is not None
, butstatus.string
is- both
status
andstatus.string
arenot 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屋!