【发布时间】:2016-02-15 20:26:35
【问题描述】:
我正在解析一个 HTML 文件并在其中搜索订单状态。有时,状态不存在,所以当我使用 BeautifulSoup 时,它会返回 NoneType。为了解决这个问题,我使用了 if-else 语句,但它也不起作用。 Python 返回:
TypeError: 'NoneType' 类型的对象没有 len()
我正在向字典添加状态,其中包含订单中的其他信息。下面的代码是一部分,它将新订单的信息添加到字典中。
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
})
【问题讨论】:
-
您尝试反转它吗?
"Not listed" if status is None else status.string[:len(status.string)-3]我怀疑python可能正在评估它...... -
您确定在 that 代码中出现错误吗? ideone.com/N2U9Kl
-
好吧我错了,那是不可重现的
-
另外,
status.string[:-3]的作用与status.string[:len(status.string)-3]完全相同 -
状态好像
is not None,但是status.string是……
标签: python parsing beautifulsoup