【问题标题】:NoneType has no attribute IF-ELSE solutionNoneType 没有属性 IF-ELSE 解决方案
【发布时间】: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


【解决方案1】:

好像有三种情况:

  1. status 是无
  2. status is not None,但status.string
  3. statusstatus.string 都是 not None

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

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 粘贴到字典中。你也可以使用异常:

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

【讨论】:

    猜你喜欢
    • 2013-05-18
    • 2023-04-03
    • 2011-02-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-02-21
    • 2021-09-14
    • 1970-01-01
    相关资源
    最近更新 更多