Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Try - Except python

Tags:

python

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

like image 788
K. chandra sekhar Avatar asked Nov 20 '25 17:11

K. chandra sekhar


1 Answers

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

like image 148
MartinStettner Avatar answered Nov 23 '25 06:11

MartinStettner



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!