下面我们来看一下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) {
-
- System.setProperty("webdriver.firefox.bin","D:\\Program Files\\Mozilla Firefox\\firefox.exe");
- WebDriver dr = new FirefoxDriver();
- dr.get("http://passport.51.com/reg2.5p");
-
-
- Select selectAge = new Select(dr.findElement(By.id("User_Age")));
- selectAge.selectByIndex(2);
-
-
- Select selectShen = new Select(dr.findElement(By.id("User_Shen")));
- selectShen.selectByValue("上海");
-
-
- Select selectTown = new Select(dr.findElement(By.id("User_Town")));
- selectTown.selectByVisibleText("浦东");
-
-
- Select selectCity = new Select(dr.findElement(By.id("User_City")));
- for(WebElement e : selectCity.getOptions())
- e.click();
- }
-
- }
从上面可以看出,对下拉框进行操作时首先要定位到这个下拉框,new 一个Selcet对象,然后对它进行操作。