python - AttributeError: 'NoneType' 对象没有属性 'get_text'

标签 python attributeerror

我正在用

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

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

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

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

有人可以建议如何处理这个错误吗?

最佳答案

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

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 的信息并相应地使用

关于python - AttributeError: 'NoneType' 对象没有属性 'get_text',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28387221/

相关文章:

python - 使用字典理解从字典列表中的选定字典创建新字典

python - 提取函数中命令行参数的名称

python - AttributeError: 'str' 对象没有属性 'search_nodes' - Python

python - AttributeError: 'NoneType' 对象没有属性 'pencolor'

python - 如何解析以空格分隔的键值对的字符串?

python - 通过 Flask 的 before_request() 强制使用 HTTPS

python - 为 Sublime Text 2 的嵌入式 Python 解释器安装 IPython

python - AttributeError: 'function' 对象没有属性 'index'

Python openpyxl 模块说 : AttributeError: 'tuple' object has no attribute 'upper'

python - 如果元素包含特定字符,则从列表或集合中删除元素