下面我們來(lái)看一下selenium webdriver是如何來(lái)處理select下拉框的,以http://xxxxxxx.com/reg2.5p這個(gè)頁(yè)面為例。這個(gè)頁(yè)面中有4個(gè)
下拉框,下面演示4種選中下拉框選項(xiàng)的方法。select處理比較簡(jiǎn)單,直接看代碼吧:)
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.support.ui.Select;
public class SelectsStudy {
/**
* @author gongjf
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
System.setProperty("webdriver.firefox.bin","D:\\Program Files\\Mozilla Firefox\\firefox.exe");
WebDriver dr = new FirefoxDriver();
dr.get("http://passport.51.com/reg2.5p");
//通過(guò)下拉列表中選項(xiàng)的索引選中第二項(xiàng)
Select selectAge = new Select(dr.findElement(By.id("User_Age")));
selectAge.selectByIndex(2);
//通過(guò)下拉列表中的選項(xiàng)的value屬性選中"上海"這一項(xiàng)
Select selectShen = new Select(dr.findElement(By.id("User_Shen")));
selectShen.selectByValue("上海");
//通過(guò)下拉列表中選項(xiàng)的可見(jiàn)文本選 中"浦東"這一項(xiàng)
Select selectTown = new Select(dr.findElement(By.id("User_Town")));
selectTown.selectByVisibleText("浦東");
//這里只是想遍歷一下下拉列表所有選項(xiàng),用click進(jìn)行選中選項(xiàng)
Select selectCity = new Select(dr.findElement(By.id("User_City")));
for(WebElement e : selectCity.getOptions())
e.click();
}
}
從上面可以看出,對(duì)下拉框進(jìn)行操作時(shí)首先要定位到這個(gè)下拉框,new 一個(gè)Selcet對(duì)象,然后對(duì)它進(jìn)行操作。