2

I am currently trying to parse an HTML page. While doing so, I have to perform

  1. Search a specific string and do some steps. (if this operation fails, go to step b)
  2. Search a specific string using a different code and do some steps. (if this operation fails, go to step 3)
  3. Search a specific string using a different code and do some steps.

I am doing like this and my question is if I have to try multiple times, how to specify try and except.

try:   
    #step 1 

except: #   ( not sure what kind of error will execute step2) 
    #step 2

except:
    #step 3

thanks

kiriloff
  • 25,609
  • 37
  • 148
  • 229

3 Answers3

8

The structure would be

try:
    step 1
except:
    try:
        step 2
    except:
        step 3

Two notes:

First, although using exceptions is a very "pythonic" way to accomplish tasks, you should check, if you couldn't use a nested if/elif/else structure.

Second, there is a HTML Parser right in the Python standard library. This question also has some HTML to DOM Parsers in the answers (i.e. Parsers that construct a DOM structure out of the HTML document, if that makes your task easier). You should be very sure that you don't want to use an existing solution before writing your own :) ...

Community
  • 1
  • 1
MartinStettner
  • 28,719
  • 15
  • 79
  • 106
4

I agree with BlackVegetable that this could probably be done with a simple if/elif, but if you have a specific reason to want to use exceptions, you can do something like this:

for method in (method1, method2, method3):
    try:
        return method(parameter)
    except VerySpecificException as _:
        pass

as a more complete example:

def method1(param):
    raise Exception('Exception: method 1 broke')

def method2(param):
    raise Exception('Exception: method 2 broke')

def method3(param):
    print param

def main():
    param = 'success!'
    for method in (method1, method2, method3):
        try:
            return method(param)
        except Exception as e:
            print e
if __name__ == '__main__':
    main()

prints:

Exception: method 1 broke
Exception: method 2 broke
success!

If either of the first methods does not break, then those methods will return success and the loop will end.

red
  • 684
  • 1
  • 6
  • 10
1

This seems like it might be best served by using if/elif:

if conditionA:
    # do something
elif conditionB:
    # do something else
elif conditionC:
    # do something completely different
else:
    # go cry in a room
BlackVegetable
  • 12,594
  • 8
  • 50
  • 82