Catching selenium error before it crashes in python
Asked Answered
R

1

0

I have a been having a problem with using selenium in my python code as the program keeps crashing. I have tried to use try, except statement to catch the error so that when it crashes I can still close it successfully but I have not been able to get it to work as the driver needs to be declared before it the exception statement Please how can I catch the crash and close it. This is what I have tried

try:
    driver = webdriver.Chrome(chrome_options=chrome_options)
except Exception as e:
    driver.close()
    driver.quit()

It insist that driver does not exists and if I declare the driver before the exception statement with no argument it gives error although I am using Chrome in this example but I intend to use it for firefox as well

Thanks

Rountree answered 25/5, 2022 at 10:7 Comment(3)
YOu need to provide the path for the chromedriver executable... geeksforgeeks.org/browser-automation-using-selenium may helpGodfrey
@PrakharParikh I have included it inide the options. Thanks very much really appreciate itRountree
I don't think it's possible. Browsers are running in separate threads. Selenium only controls them. It applies to any thread - you can send a signal, use sockets, etc, but if exception occurs in a different thread, you can only read this exception from the main thread - exception already occurred, so you can't control it.Whitecollar
B
1

Selenium's driver might be used as context manager (i.e. harnessed using with statement), consider following example

with webdriver.Chrome(chrome_options=chrome_options) as driver:
    driver.get("http://www.example.com")
    print(driver.page_source)

When so used it should take care of ending both in case of crash and lack thereof, so you do not need to call driver.close and driver.exit.

Bathroom answered 25/5, 2022 at 10:15 Comment(2)
I tried it it was not working. Thanks for the helpRountree
it did not workRountree

© 2022 - 2024 — McMap. All rights reserved.