AttributeError: 'NoneType' object has no attribute 'get_text'

匿名 (未验证) 提交于 2019-12-03 02:23:02

问题:

I am parsing HTML text with

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

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).

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

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?

回答1:

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



标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!