Reputation: 217
I use selenium webdriver, how can i check if the element should not be present in the page and I'm testing python. Can anyone suggest any solutions to this problem.
Thanks a lot.
Upvotes: 2
Views: 2086
Reputation: 1378
try:
driver.find_elements_by_xpath('//*[@class="should_not_exist"]')
should_exist = False
except:
should_exist = True
if not should_exist:
// Do something
Upvotes: 0
Reputation: 7246
You could do this a number of ways. Lazy would be something like this.
# Import these at top of page
import unittest
try: assert '<div id="Waldo" class="waldo">Example</div>' not in driver.page_source
except AssertionError, e: self.verificationErrors.append("Waldo incorrectly appeared in page source.")
Or you could import Expected conditions and asserting it returns presence_of_element_located is not True. Notice true is caps sensitive and presence_of_element_located either returns True or Not Null so assertFalse wouldn't be an easier way to phrase this.
# Import these at top of page
import unittest
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions as EC
try: assert EC.presence_of_element_located( (By.XPATH, '//*[@id="Waldo"]') ) is not True
except AssertionError, e: self.verificationErrors.append('presence_of_element_located returned True for Waldo')
Or like Raj said, you could use find_elements and assert there are 0.
import unittest
waldos = driver.find_elements_by_class_name('waldo')
try: self.assertEqual(len(waldos), 0)
except AssertionError, e: self.verificationErrors.append('Found ' + str(len(waldos)) + ' Waldi.')
You could also assert that a NoSuchElementException will occur.
# Import these at top of page
import unittest
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.common.exceptions import NoSuchElementException
try:
with self.assertRaises(NoSuchElementException) as cm:
driver.find_element(By.CSS_SELECTOR, 'div.waldo')
except AssertionError as e:
raise e
Upvotes: 2
Reputation: 2002
You can create a method IsElementPresent which will return whether element is present on page or not. You can call this method in your test case.
public boolean IsElementPresent(String locator, String locatorvalue)
{
try
{
if(locator.equalsIgnoreCase("id"))
{
driver.findElement(By.id(locatorvalue));
}
return true;
}
catch (NoSuchElementException e)
{
return false;
}
}
Upvotes: -2
Reputation: 2938
yes try below its one liner and simple to use
if(driver.findElements(By.xpath("yourXpath/your locator stratgey")).size() >0){
// if size is greater then zero that means element
// is present on the page
}else if(!(driver.findElements(By.xpath("yourXpath/your locator stratgey")).size() >0)){
// if size is smaller then zero that means
// element is not present on the page
}
Upvotes: 1