簡體   English   中英

Python - 如何檢查頁面中不應該存在的元素

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM