【发布时间】:2014-06-23 13:10:30
【问题描述】:
我正在写一些功能测试,做一些简单的单页测试需要5分钟,因为find_element函数在找不到元素时需要30秒才能完成。我需要测试是否存在元素而不必等待超时。我一直在寻找,但到目前为止还没有找到 find_element() 的任何替代方法。这是我的代码:
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
谢谢。
嗯,我遵循了这里和其他链接中的大部分建议,最终未能实现目标。当找不到元素时,它具有完全相同的行为,需要 30 秒:
# 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
这是使用获取所有元素的想法的第二种方法
# 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
注意,我不接受之前的回答,因为遵循海报的建议并没有产生成功的结果。
【问题讨论】: