Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.1k views
in Technique[技术] by (71.8m points)

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

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...