【问题标题】:Verify element not present in the DOM验证 DOM 中不存在的元素
【发布时间】:2021-01-08 09:29:36
【问题描述】:
我目前正在尝试验证该元素是否存在于 DOM 中:我已经编写了这个函数:
element = self.driver.find_element_by_xpath(xpath)
if element.is_displayed():
raise Exception("Element should not be found")
else:
pass
我正在接收消息:
Unable to locate element
【问题讨论】:
标签:
python
selenium
selenium-webdriver
webdriverwait
【解决方案1】:
请使用 find_elements_by_xpath。
if len(self.driver.find_elements_by_xpath(xpath)) > 0:
raise Exception("Element should not be found")
else:
pass
【解决方案2】:
is_displayed() 只检查元素是否显示给用户(可见) - 而不是存在。
当找不到元素时,find_element_by_xpath() 也会引发NoSuchElementException,因此您应该使用try/catch 包装整个代码,如下所示
from selenium.common.exceptions import NoSuchElementException
try:
element = self.driver.find_element_by_xpath(xpath)
if element.is_displayed():
raise Exception("Element should not be found")
else:
print("element is not shown")
except NoSuchElementException:
print("element doesn't exist in the tree")
【解决方案3】:
要验证DOM Tree 中不存在该元素,您需要为invisibility_of_element_located() 诱导WebDriverWait,您可以使用以下逻辑:
try:
WebDriverWait(driver, 20).until(EC.invisibility_of_element_located((By.XPATH, "xpath")))
print("Element no more found")
except TimeoutException:
print("Element should not be found")
注意:您必须添加以下导入:
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions as EC
参考
您可以在以下位置找到一些相关讨论: