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

查看:29
本文介绍了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 except 轻松做到这一点,它的工作原理是:如果 try 块中的给定命令被执行而没有任何错误,那么它永远不会进入但是,如果在 try 块中执行命令时出现错误,则它会搜索相关的 except 处理程序并执行相应的 except 块中的命令.try except 块的常见用途是防止程序在遇到问题时停止.

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: -"

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

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天全站免登陆