AttributeError:"NoneType"对象没有属性"get_text" [英] AttributeError: 'NoneType' object has no attribute 'get_text'

查看:172
本文介绍了AttributeError:"NoneType"对象没有属性"get_text"的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用

Telephone = soup.find(itemprop="telephone").get_text()

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

In the case a Telephone number is in the HTML after the itemprop tag, I receive a number and get the output ("Telephone Number: 34834243244", for instance).

当然,如果找不到电话号码,我会收到AttributeError: 'NoneType' object has no attribute 'get_text'.很好.

Of course, I receive AttributeError: 'NoneType' object has no attribute 'get_text' in the case no telephone number is found. That is fine.

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

However, in this case I would like Python not to print an error message and instead set Telephone = "-" and get the output "Telephone Number: -".

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

Can anybody advise how to handle this error?

推荐答案

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

You can easily do that by using try except in Python, It works like: if the given commands in the try block are executed without any error then it never enters the except block, However if there is some error while executing the commands in the try block then it searched for the relevant except handler and executes the commands in corresponding except block. The common use of try except block is to prevent the program from halting if some issue is encountered.

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

您始终可以同时使用多个命令(除命令以外)来相应地处理各种异常.

You can always use more than one except commands at the same time to handle various exceptions accordingly.

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

The fully structured exception handling looks something like this:

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

您可以找到有关异常处理的更多信息并相应地使用

You can find more about Exception handling and use accordingly

这篇关于AttributeError:"NoneType"对象没有属性"get_text"的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆