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

Zac*_*urt 5 python selenium exception selenium-rc selenium-webdriver

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>
Run Code Online (Sandbox Code Playgroud)

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])
Run Code Online (Sandbox Code Playgroud)

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

有什么办法可以自动尝试driver.switch_to_window() invocation if an exception occurs?

Mis*_*sev 4

<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>

这?

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)
Run Code Online (Sandbox Code Playgroud)