下面我們來看一下selenium webdriver是如何來處理select下拉框的,以http://passport.51.com/reg2.5p這個頁面爲例。這個頁面中有4個下拉框,下面演示4種選中下拉框選項的方法。select處理比較簡單,直接看代碼吧:)
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 {
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");
//通過下拉列表中選項的索引選中第二項,即2011年
Select selectAge = new Select(dr.findElement(By.id("User_Age")));
selectAge.selectByIndex(2);
//通過下拉列表中的選項的value屬性選中"上海"這一項
Select selectShen = new Select(dr.findElement(By.id("User_Shen")));
selectShen.selectByValue("上海");
//通過下拉列表中選項的可見文本選中"浦東"這一項
Select selectTown = new Select(dr.findElement(By.id("User_Town")));
selectTown.selectByVisibleText("浦東");
//這裏只是想遍歷一下下拉列表所有選項,用click進行選中選項
Select selectCity = new Select(dr.findElement(By.id("User_City")));
for(WebElement e : selectCity.getOptions())
e.click();
}
}
從上面可以看出,對下拉框進行操作時首先要定位到這個下拉框,new 一個Selcet對象,然後對它進行操作。
INFO comes from :http://jarvi.iteye.com/blog/1450883