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?
<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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With