Java+Selenium3自動化入門4---Select多選框下拉列表

       在做自動化的過程中我們會遇到很多的控件,有的控件在WebDriver中都有封裝好的API,我們使用這些方法來操作會提高我們的測試用例編寫效率和準確性,今天我就來介紹下關於select多選框的操作方法

        在Selenium中,針對html的標籤select多選下拉列表有幾種方法:

selectByIndex(index);  //根據索引選擇
selectByValue(value); //根據value屬性選擇
selectByVisibleText(text); //根據選項文字選擇
注意的是:
*index是從0開始的
**Value是option標籤的一個屬性值,並不是顯示在下拉框中的值
***VisibleText是在option標籤中間的值,是顯示在下拉框的值  

       四種取消方法:

deselectByIndex(0);
deselectByValue(value);
deselectByVisibleText(Text);
deselectAll();       //取消所有選中
<!--此部分爲HTML代碼,供測試時使用-->
<html>
	<head>
		<title>
			Selenium for Select  
		</title>
	</head>
	<body>
		
		<font size="5" color="red">選擇你的興趣愛好:</font>
		<!-- multiple=multiple指的是允許多選-->
		<select name="lions" size=6 multiple=multiple>
			<option id="basketball" value="basketball">籃球</option>
			<option id="billiards" value="billiards">檯球</option>
			<option id="table_tennis" value="table_tennis">乒乓球</option>
			<option id="swimming" value="swimming">游泳</option>
			<option id="girl" value="girl">撩妹</option>
			<option id="default" value="默認" selected="selected">--請選擇--</option>
		</select>
	</body>
</html>

頁面效果如下圖:



測試代碼:

package com.yumeihu.D1;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.support.ui.Select;

public class LionsMultipleOptionDropList {
/*
* Today is  very  hot  2018-06-13
*/
    
    public static void main(String[] args) throws Exception {    
  
        WebDriver driver = new FirefoxDriver();        
        driver.manage().window().maximize();    
        String Url = "file:///C:/Users/ber.ear/Desktop/lions.htm";
        driver.get(Url); 
        //使用 name 屬性找到頁面上 name 屬性爲 lions的下拉列表元素
        Select dropList = new Select(driver.findElement(By.name("lions")));
        //使用選擇項索引選擇"籃球"選項
        dropList.selectByIndex(0);
        //使用 value 屬性值選擇"游泳"選項
        dropList.selectByValue("swimming");
        //使用選項文字選擇"乒乓球"選項
        dropList.selectByVisibleText("乒乓球");
        //等待 3 秒
        Thread.sleep(3000);
        //deselectAll 方法表示取消所有選項的選中狀態
        dropList.deselectAll();
        //再次選中 3 個選項
        dropList.selectByIndex(2);
        dropList.selectByValue("table_tennis");
        dropList.selectByVisibleText("籃球");
        //deselectByIndex 方法表示取消索引爲 3 的選項的選中狀態,因爲索引Index是從0開始的
        dropList.deselectByIndex(2); 
        
    }
}
That's all,通過Select提供的方法和屬性,我們可以對標準select下拉框進行任何操作,但是對於非select標籤的僞下拉框(即input標籤寫的假下拉框!!),就需要用其他的方法了,我們下一節說說如何遍歷下拉框中的數據。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章