0

I am trying to catch an exception thrown by Selenium. When the exception is thrown I would like to restart the scraping process.

try:
  startScraping(rootPage)
except (InvalidSessionIdException):
  startScraping(rootPage)
finally:
  driver.close()

Above is the code I am using.

The problem I am facing is that when an InvalidSessionIdException occurs the script still stops execution and shows a stacktrace.

2
  • 3
    Well? Please show us the stacktrace. The stacktrace exists for a reason.
    – Chase
    Commented Jan 27, 2021 at 13:46
  • 1
    the second startScraping(rootPage) (in the except block) is not protected by any try/except block... Commented Jan 27, 2021 at 13:56

2 Answers 2

3

the second startScraping(rootPage) (in the except block) is not protected by any try/except block...

If an exception occurs, retrying immediately is probably bound to fail ... again. I would

  • catch the exception
  • print a meaningful warning
  • wait a while
  • repeat until it works, or a given number of times with a for loop

like this

import time
nb_retries = 10
for nb_attempts in range(nb_retries):
    try:
      startScraping(rootPage)
      break  # success, exit the loop
    except InvalidSessionIdException as e:
      print("Warning: {}, attempt {}/{}".format(e,nb_attempts+1,nb_retries))
      time.sleep(1)
else:
   # loop went through after 10 attempts and no success
   print("unable to scrape after {} retries".format(nb_retries))

driver.close()
1

Try this if you want to restart the process and ignoring the exception:

while True:
    try:
      startScraping(rootPage)
      break # after finishing the scraping process
    except (InvalidSessionIdException):
      pass # or print the excepion

driver.close()

as mentioned in the code, you can print the exception or do any other exception handling you may want.

2
  • that probably works, but 1) please explain that OP gets an exception because he tries to scrape again in the exception handler 2) maybe some delay or warning should be good to avoid intensive infinite loop without any message Commented Jan 27, 2021 at 13:53
  • @Jean-FrançoisFabre 1) In the original code when an exception occurs for the first time the control goes to the except part. but when the exception occurs for the second time there would be no other except part to handle the new exception so the program crashes. 2) I agree with you. It's achievable by adding extra code (e.g sleep) before pass. Commented Jan 27, 2021 at 14:02

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.