2

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
  • 1
    Two choices, either: test is None beforehand; or try and catch the AttributeError. Commented Feb 7, 2015 at 20:53

1 Answer 1

8

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

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.