[英]Python - How to check a element that should not exist in the page
我使用 selenium webdriver,如何检查该元素是否不应该出现在页面中并且我正在测试 python。 任何人都可以建议任何解决此问题的方法。
非常感谢。
您可以通过多种方式做到这一点。 懒惰会是这样的。
# 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街。 请注意,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')
或者像拉吉说,你可以使用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
是的,在它的一个衬里下方尝试,并且易于使用
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
}
try:
driver.find_elements_by_xpath('//*[@class="should_not_exist"]')
should_exist = False
except:
should_exist = True
if not should_exist:
// Do something
您可以创建一个 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;
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.