断言元素不存在python Selenium

mik*_*ike 2 python selenium python-2.7

我正在使用Selenium python并寻找一种断言元素不存在的方式,例如:

assert not driver.find_element_by_xpath("locator").text== "Element Text"
Run Code Online (Sandbox Code Playgroud)

And*_*son 5

您可以在下面使用:

assert not len(driver.find_elements_by_xpath("locator"))
Run Code Online (Sandbox Code Playgroud)

如果locator找不到与您的元素匹配的元素,或者AssertionError至少找到1个元素,则应该通过断言

注意,如果元素是由某些元素动态生成的,JavaScript则它可能在执行断言DOM 出现。在这种情况下,您可以实现ExplicitWait

从selenium.webdriver.common.by导入从selenium.webdriver.support.ui导入从selenium.webdriver.support导入WebDriverWait从EC导入期望的条件

try:
    WebDriverWait(driver, 10).until(EC.presence_of_element_located((By.XPATH, "locator")))
    not_found = False
except:
    not_found = True

assert not_found
Run Code Online (Sandbox Code Playgroud)

在这种情况下,我们将获得AssertionError元素是否在10秒内出现在DOM中