《手把手教你》系列技巧篇(四十八)-java+ selenium自動化測試-判斷元素是否可操作(詳解教程)


1.簡介

webdriver有三種判斷元素狀態的方法,分別是isEnabled,isSelected 和 isDisplayed,其中isSelected在前面的內容中已經簡單的介紹了,isSelected表示查看元素是否被選中,一般用在勾選框中(多選或者單選),isDisplayed表示查看選中是否可見。isEnabled表示查什么呢?isEnabled表示查看元素是否可以進行操作,比如,點擊,輸入等。

2.isEnabled()源碼

/**
* Is the element currently enabled or not? This will generally return true for everything but
* disabled input elements.
* <p>
* See <a href="https://w3c.github.io/webdriver/#is-element-enabled">W3C WebDriver specification</a>
* for more details.
*
* @return True if the element is enabled, false otherwise.
*/
boolean isEnabled();

 從上邊的源碼中的注釋可以看出isEnabled()方法是用來判斷頁面元素是否可操作。可操作返回true,不可操作返回false。

3.isEnabled()用法

List<WebElement> targetElement =  driver.findElements(By.xpath("xpath_your_expected_element"));

    try {

        if(targetElement>=1) {

            if(targetElement.isEnabled()) {

                System.out.println("Element is operable");

            }else {

                System.out.println("Element is found, but hidden on the page");
            
            }

        }else {

            System.out.println("Element not found on the page");

        }
    }catch (NoSuchElementException e) {

        System.out.println("Exception in finding the element:" + e.getMessage());

    }

4.項目實戰

 宏哥這里用度娘的首頁搜索輸入框舉例,判斷這個搜索輸入框是否可以輸入內容,然后利用JavaScript加上屬性readonly后,再次判斷是否可以輸入內容,對你沒看錯就是這么玩。

4.1測試用例(思路)

1.訪問度娘首頁

2.定位搜索輸入框,判斷其是否可以操作(輸入搜索內容)

3.給搜索輸入框通過JavaScript添加readonly屬性

4.再次判斷搜索輸入框是否可以操作(輸入搜索內容)

4.2代碼設計

4.3參考代碼

package lessons;

import java.util.concurrent.TimeUnit;

import org.openqa.selenium.By;
import org.openqa.selenium.JavascriptExecutor;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;

/**
 * @author: 北京-宏哥
 * 
 * @公眾號:北京宏哥
 * 
 * 《手把手教你》系列技巧篇(四十八)-java+ selenium自動化測試-判斷元素是否可操作(詳解教程)
 *
 * 2021年11月20日
 */
public class testEnabled {
    
    public static void main(String[] args) throws Exception {  
            
            System.setProperty("webdriver.chrome.driver", ".\\Tools\\chromedriver.exe");  
               
            WebDriver driver = new ChromeDriver();  
         
            driver.manage().window().maximize();  
           
            driver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS);
            //訪問度娘首頁 
            driver.get("https://www.baidu.com/");  
            
            WebElement searchInputBox = driver.findElement(By.id("kw"));
            if(searchInputBox.isEnabled()==true){
                System.out.println("百度首頁的搜索輸入框可以輸入內容!");
            }
            //給搜索輸入框通過JavaScript添加disable屬性
            JavascriptExecutor jsExecutor = (JavascriptExecutor) driver;
            String js = "document.getElementById('kw').setAttribute('disabled', '')"; 
            jsExecutor.executeScript(js);
            Thread.sleep(5000);
            WebElement searchInputBox1 = driver.findElement(By.className("s_ipt"));
            
            //再次判斷搜索輸入框是否可以操作(輸入搜索內容)
            if(!searchInputBox1.isEnabled()){
                System.out.println("百度首頁的搜索輸入框不可以輸入內容!");
            }
            driver.quit();
    }

}

4.4運行代碼

1.運行代碼,右鍵Run AS->Java Appliance,控制台輸出,如下圖所示:

2.運行代碼后電腦端的瀏覽器的動作(宏哥點擊輸入框也不允許輸入內容),如下小視頻所示:

3.可能小伙伴后者童鞋們沒有注意宏哥在錄屏中點擊輸入框,通過JavaScript給輸入框加入不可操作屬性,宏哥在這里演示一下,仍然給輸入框輸入內容就會報如下錯誤:element not interactable(元素不可交互)。如下圖所示:

4.當然了你也可以通過F12查看元素已經加上了不可以操作的屬性,如下圖所示:

5.小結

  好了,今天時間也不早了,宏哥就分享到這里,感謝您耐心地閱讀。

6.拓展

如果你不想用或者覺得selenium自帶的API不能滿足你的要求,你也可以根據自己的需要定義一個API,然后進行調用使用。

 6.1自定義的API

//自定義一個判斷頁面元素是否存在的函數或者方法IsElementPresent
private boolean IsElementPresent(By by){
    try{
        //如果傳入的參數by能夠找到頁面元素,則函數返回“true”,表示成功
        //找到頁面元素
        driver.findElement(by);
        return true;
    }catch(NoSuchElementException e){
        //如果傳入的參數by沒有找到頁面元素,則函數返回“false”,
        //表示沒有成功的找到頁面元素
        return false;
    }
}

6.2測試方法

@Test
public void testIsElement1(){
        
    driver.manage().window().maximize();  
           
    driver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS);
    //訪問搜狗首頁
    driver.get("http://www.baidu.com");
        
    //調用ISElementPresent函數,查找ID為“query”的頁面元素對象
    if(IsElementPresent(By.id("kw"))){
        //如果定位到頁面元素,則把頁面元素對象存儲到searchInputBox變量中
        WebElement searchInputBox = driver.findElement(By.id("kw"));
        /*判斷searchInputBox變量對象是否處於可用狀態。如果處於可用狀態,則輸入
        “搜狗首頁的搜索輸入框被成功找到!”*/
        if(searchInputBox.isEnabled()==true){
            searchInputBox.sendKeys("百度首頁的搜索輸入框被成功找到!");
        }
    }else{
        //如果首頁輸入框元素未被找到。則將此測試用例的設置為失敗狀態
        //打印失敗原因
        Assert.fail("頁面上的輸入框元素未被找到!");
    }
}

6.3參考代碼

package lessons;

import java.util.concurrent.TimeUnit;

import junit.framework.Assert;

import org.junit.Test;
import org.openqa.selenium.By;
import org.openqa.selenium.NoSuchElementException;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;

/**
 * @author: 北京-宏哥
 * 
 * @公眾號:北京宏哥
 * 
 * 《手把手教你》系列技巧篇(四十八)-java+ selenium自動化測試-判斷元素是否可操作(詳解教程)
 *
 * 2021年11月20日
 */
public class testIsElement {
    
    WebDriver driver = new ChromeDriver();  
    //自定義一個判斷頁面元素是否存在的函數或者方法IsElementPresent
    private boolean IsElementPresent(By by){
        try{
            //如果傳入的參數by能夠找到頁面元素,則函數返回“true”,表示成功
            //找到頁面元素
            driver.findElement(by);
            return true;
        }catch(NoSuchElementException e){
            //如果傳入的參數by沒有找到頁面元素,則函數返回“false”,
            //表示沒有成功的找到頁面元素
            return false;
        }
    }

    @Test
    public void testIsElement1(){
        
        driver.manage().window().maximize();  
           
        driver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS);
        //訪問搜狗首頁
        driver.get("http://www.baidu.com");
        
        //調用ISElementPresent函數,查找ID為“query”的頁面元素對象
        if(IsElementPresent(By.id("kw"))){
            //如果定位到頁面元素,則把頁面元素對象存儲到searchInputBox變量中
            WebElement searchInputBox = driver.findElement(By.id("kw"));
            /*判斷searchInputBox變量對象是否處於可用狀態。如果處於可用狀態,則輸入
            “搜狗首頁的搜索輸入框被成功找到!”*/
            if(searchInputBox.isEnabled()==true){
                searchInputBox.sendKeys("百度首頁的搜索輸入框被成功找到!");
            }
        }else{
            //如果首頁輸入框元素未被找到。則將此測試用例的設置為失敗狀態
            //打印失敗原因
            Assert.fail("頁面上的輸入框元素未被找到!");
        }
    }

}

6.4運行代碼

1.運行代碼,右鍵Run AS->Junit Test,控制台輸出,如下圖所示:

2.運行代碼后電腦端的瀏覽器的動作,如下小視頻所示:


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM