【问题标题】:AttributeError: 'NoneType' object has no attribute 'get_text'AttributeError:“NoneType”对象没有属性“get_text”
【发布时间】:2015-04-07 20:40:35
【问题描述】:

我正在用

解析 HTML 文本
Telephone = soup.find(itemprop="telephone").get_text()

如果电话号码在 HTML 中 itemprop 标记之后,我会收到一个号码并得到输出(例如,"Telephone Number: 34834243244")。

当然,如果没有找到电话号码,我会收到AttributeError: 'NoneType' object has no attribute 'get_text'。没关系。

但是,在这种情况下,我希望 Python 不打印错误消息,而是设置 Telephone = "-" 并获取输出 "Telephone Number: -"

谁能建议如何处理这个错误?

【问题讨论】:

  • 两个选择,要么:预先测试is None;或try 并抓住AttributeError

标签: python attributeerror


【解决方案1】:

您可以通过在 Python 中使用 try except 轻松做到这一点,它的工作原理如下:如果 try 块中的给定命令执行时没有任何错误,则它永远不会进入 except 块,但是如果在执行命令时出现错误然后在 try 块中搜索相关的 except 处理程序并执行相应的 except 块中的命令。 try except 块的常见用途是防止程序在遇到问题时停止。

try:
    Telephone = soup.find(itemprop="telephone").get_text()
except AttributeError:
    print "Telephone Number: -"

您始终可以同时使用多个 except 命令来相应地处理各种异常。

完全结构化的异常处理如下所示:

try:
    result = x / y
except ZeroDivisionError:
    print "division by zero!"
else:
    print "result is", result
finally:
    print "executing finally clause"

你可以找到更多关于Exception handling的信息并相应地使用

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-12-28
    • 1970-01-01
    • 2020-05-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-07-25
    • 1970-01-01
    相关资源
    最近更新 更多