Python - 如何检查页面中不应存在的元素

时间:2016-05-05 09:25:14

标签: python validation selenium webdriver assert

我使用selenium webdriver,如何检查该元素是否应该出现在页面中并且我正在测试python。任何人都可以建议解决这个问题。

非常感谢。

4 个答案:

答案 0 :(得分:2)

你可以通过多种方式做到这一点。懒惰就是这样的。

# 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.")

或者您可以导入预期条件并断言它返回presence_of_element_located不是 T rue。注意true是大写敏感,并且presence_of_element_located返回True或Not Null,因此assertFalse不会是一种更简单的方法来表达这一点。

# 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')

或者像Raj说的那样,你可以使用find_element s 并声明它有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.')

您还可以断言将发生NoSuchElementException。

# 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

答案 1 :(得分:1)

是尝试低于其一个班轮并且使用简单

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
        }

答案 2 :(得分:0)

try: 
    driver.find_elements_by_xpath('//*[@class="should_not_exist"]')
    should_exist = False
except:
    should_exist = True

if not should_exist:
    // Do something

答案 3 :(得分:-2)

您可以创建一个方法IsElementPresent,它将返回页面上是否存在元素。您可以在测试用例中调用此方法。

public boolean IsElementPresent(String locator, String locatorvalue) 
{
    try 
    {   
        if(locator.equalsIgnoreCase("id"))
        {
            driver.findElement(By.id(locatorvalue));                
        }
        return true;
        }
    catch (NoSuchElementException e) 
    {
        return false;
    }
}