Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Set up a default exception handler when unable to locate an element in selenium?

It's quite often the case that my selenium script will be running, and then all of a sudden it will crash with an error:

<class 'selenium.common.exceptions.NoSuchElementException'>
Message: u'Unable to locate element: {"method":"id","selector":"the_element_id"}' 
<traceback object at 0x1017a9638>

And if I run in interactive mode (python -i myseltest.py), if I simply do something like:

driver.switch_to_window(driver.window_handles[0])

And then run the specific find_element_by_id() again, it will succeed.

Is there any way to automatically attempt the driver.switch_to_window() invocation if an exception occurs?

like image 482
Zack Burt Avatar asked Oct 08 '22 17:10

Zack Burt


1 Answers

<UPDATE>
First, consider using implicit wait, because this problem occurs mostly when element's presence is triggered by an on-page javascript, and you might get a few seconds long delay between DOMReady event and js functions or ajax queries execution.
</UPDATE>

This?

from selenium.webdriver import Firefox  
from selenium.webdriver.support.ui import WebDriverWait  

from selenium.common.exceptions import TimeoutException  
from selenium.common.exceptions import NoSuchElementException

class MyFirefox(Firefox):

    RETRIES = 3
    TIMEOUT_SECONDS = 10

    def find_element_by_id(self, id):
        tries = 0
        element = None

        while tries < self.RETRIES:
            try:
                element = WebDriverWait(self, self.TIMEOUT_SECONDS).until(
                    lambda browser: super(MyFirefox, browser).find_element_by_id(id)
                )   
            except TimeoutException:
                tries = tries + 1
                self.switch_to_window(self.window_handles[0])
                continue
            else:
                return element

        raise NoSuchElementException("Element with id=%s was not found." % id)
like image 120
Misha Akovantsev Avatar answered Oct 13 '22 09:10

Misha Akovantsev