我使用 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.")
或者您可以导入 Expected conditions 并断言它返回 presence_of_element_located is not True。请注意,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_elements 并断言有 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
