I have the following code, which is currently working. But, if an user closes the Chrome Windows or chrome crashes, all the articles loaded in the for loop are updated with an error. In that case, I need to execute again the driver.start_driver() function. How can I catch the chrome not reachable exception so I can execure drier.start_driver() in case of failure?
I've tried the following, but is not working:
try:...
except WebDriverException as e:...
But I get:
NameError: name 'WebDriverException' is not defined
This is the current code I have:
driver=driver.start_driver()
for index, row in listado_productos.iterrows():
try:
driver.get(url)
amount = driver.find_element(By.CSS_SELECTOR, "div.ui-header_subtitle a.test span.ui-subtitle").text
...
db.update_article_date(article_df)
except Exception as e:
db.update_article_error(row['product_id'])
driver.close()
And this is the traceback of the "Chrome not reachable" error:
Traceback (most recent call last):
File "<string>", line 2, in <module>
File "c:...\lib\site-packages\selenium\webdriver\remote\webdriver.py", line 976, in find_element
return self.execute(Command.FIND_ELEMENT, {
File "c:\...\lib\site-packages\selenium\webdriver\remote\webdriver.py", line 321, in execute
self.error_handler.check_response(response)
File "c:\ArchivosSinOnedrive\repositorios\lib\site-packages\selenium\webdriver\remote\errorhandler.py", line 242, in check_response
raise exception_class(message, screen, stacktrace)
selenium.common.exceptions.WebDriverException: Message: chrome not reachable
(Session info: chrome=94.0.4606.71)
CodePudding user response:
You can have a ladder of except for a single try like this, to handle NoSuchElementException , WebDriverException and other exception like below :
driver=driver.start_driver()
for index, row in listado_productos.iterrows():
try:
driver.get(url)
amount = driver.find_element(By.CSS_SELECTOR, "div.ui-header_subtitle a.test span.ui-subtitle").text
...
db.update_article_date(article_df)
except NoSuchElementException as noelement:
print('do something in case of no such element exception')
except WebDriverException as driver_exception:
print('do something in case of webdriver exception')
print('do something here')
except Exception as e:
db.update_article_error(row['product_id'])
driver.close()