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?
Asked
Active
Viewed 5,801 times
6
-
show us the code,how do you do it? – root Oct 09 '12 at 05:36
-
1Yes, the exact xpath expression here is important here – bdonlan Oct 09 '12 at 05:48
2 Answers
8
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

Santoshsarma
- 5,627
- 1
- 24
- 39
-
how do you do this in python? `driver.implicitly_wait(0)` does not do any change. Seems it keeps the value given in the first call. – Anubis Mar 19 '18 at 10:54
0
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())

sbha
- 9,802
- 2
- 74
- 62

Carl Brubaker
- 1,602
- 11
- 26