Trying to verify after few GUI operations some button does not exist (expected not to be present). I am using find_element_by_xpath() but its very slow. Any solution of timeout?
Actually WebDriver's find_element method will wait for implicit time for the element if the specified element is not found.
There is no predefined method in WebDriver like isElementPresent() to check. You should write your own logic for that.
Logic
public boolean isElementPresent()
{
try
{
set_the_implicit time to zero
find_element_by_xpath()
set_the_implicit time to your default time (say 30 sec)
return true;
}
catch(Exception e)
{
return false;
}
}
See : http://goo.gl/6PLBw
If you are trying to check that an element does not exist, the easiest way to do that is using a with
statement.
from selenium.common.exceptions import NoSuchElementException
def test_element_does_not_exist(self):
with self.assertRaises(NoSuchElementException):
browser.find_element_by_xpath()
As far as a timeout, I like the one from "Obey The Testing Goat" .
# Set to however long you want to wait.
MAX_WAIT = 5
def wait(fn):
def modified_fn(*args, **kwargs):
start_time = time.time()
while True:
try:
return fn(*args, **kwargs)
except (AssertionError, WebDriverException) as e:
if time.time() - start_time > MAX_WAIT:
raise e
time.sleep(0.5)
return modified_fn
@wait
def wait_for(self, fn):
return fn()
# Usage - Times out if element is not found after MAX_WAIT.
self.wait_for(lambda: browser.find_element_by_id())
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.