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

23,971

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

Share:
23,971

Related videos on Youtube

RC_Data
Author by

RC_Data

Updated on October 25, 2020

Comments

  • RC_Data
    RC_Data over 3 years

    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?

    • jonrsharpe
      jonrsharpe about 9 years
      Two choices, either: test is None beforehand; or try and catch the AttributeError.