Python如何检查pag中不应该存在的元素

2024-04-24 22:37:16 发布

您现在位置:Python中文网/ 问答频道 /正文

我使用selenium webdriver,如何检查元素是否不应该出现在页面中,并且我正在测试python。有谁能提出解决这个问题的办法吗。在

非常感谢。在


Tags: 元素selenium页面webdriver办法
3条回答

是的,试试下面的一个班轮和简单的使用

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
        }

你可以用很多方法。懒惰就是这样。在

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

或者,您可以导入预期的条件,并断言它返回“元素”的存在“不在True”。注意,true是区分大小写的,而presence_of \u element_located要么返回true,要么返回Not Null,所以assertFalse并不是一种更容易的表达方式。在

^{pr2}$

或者像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
try: 
    driver.find_elements_by_xpath('//*[@class="should_not_exist"]')
    should_exist = False
except:
    should_exist = True

if not should_exist:
    // Do something

相关问题 更多 >