I am writing some functional tests and it takes 5 minutes to do some simple single-page testing because the find_element function takes 30 seconds to complete when the element is not found. I need to test for the absence of an element without having to wait for a timeout. I've been searching but so far have not found any alternative to find_element(). Here's my code:
def is_extjs_checkbox_selected_by_id(self, id):
start_time = time.time()
find_result = self.is_element_present(By.XPATH, "//*[@id='" + id + "'][contains(@class,'x-form-cb-checked')]") # This line is S-L-O-W
self.step(">>>>>> This took " + str( (time.time() - start_time) ) + " seconds")
return find_result
def is_element_present(self, how, what):
try: self.driver.find_element(by=how, value=what)
except NoSuchElementException, e: return False
return True
Thanks.
Well, I followed most of the recommendations here and in the other links and in the end, and have failed to achieve the goal. It has the exact same behavior of taking 30 seconds when the element is not found:
# Fail
def is_element_present_timeout(self, id_type, id_locator, secs_wait_before_testing):
start_time = time.time()
driver = self.driver
time.sleep(secs_wait_before_testing)
element_found = True
try:
element = WebDriverWait(driver, 0).until(
EC.presence_of_element_located((id_type, id_locator))
)
except:
element_found = False
elapsed_time = time.time() - start_time
self.step("elapsed time : " + str(elapsed_time))
return element_found
Here's a second approach using the idea of getting all elements
# Fail
def is_element_present_now(self, id_type, id_locator):
driver = self.driver
# This line blocks for 30 seconds if the id_locator is not found, i.e. fail
els = driver.find_elements(By.ID, id_locator)
the_length = els.__len__()
if the_length == 0:
result = False
else:
result = True
self.step('length='+str(the_length))
return result
Note, I've unaccepted previous answer since following poster's advice did not produce a successful result.