zoukankan      html  css  js  c++  java
  • selenium webdriver学习(八)------------如何操作select下拉框(转)

    下面我们来看一下selenium webdriver是如何来处理select下拉框的,以http://passport.51.com/reg2.5p这个页面为例。这个页面中有4个下拉框,下面演示4种选中下拉框选项的方法。select处理比较简单,直接看代码吧:)

    Java代码  收藏代码
    1. import org.openqa.selenium.By;  
    2. import org.openqa.selenium.WebDriver;  
    3. import org.openqa.selenium.WebElement;  
    4. import org.openqa.selenium.firefox.FirefoxDriver;  
    5. import org.openqa.selenium.support.ui.Select;  
    6.   
    7. public class SelectsStudy {  
    8.   
    9.     /** 
    10.      * @author gongjf 
    11.      */  
    12.     public static void main(String[] args) {  
    13.         // TODO Auto-generated method stub  
    14.         System.setProperty("webdriver.firefox.bin","D:\Program Files\Mozilla Firefox\firefox.exe");    
    15.         WebDriver dr = new FirefoxDriver();  
    16.         dr.get("http://passport.51.com/reg2.5p");  
    17.           
    18.         //通过下拉列表中选项的索引选中第二项,即2011年  
    19.         Select selectAge = new Select(dr.findElement(By.id("User_Age")));  
    20.         selectAge.selectByIndex(2);  
    21.           
    22.         //通过下拉列表中的选项的value属性选中"上海"这一项  
    23.         Select selectShen = new Select(dr.findElement(By.id("User_Shen")));  
    24.         selectShen.selectByValue("上海");  
    25.           
    26.         //通过下拉列表中选项的可见文本选 中"浦东"这一项  
    27.         Select selectTown = new Select(dr.findElement(By.id("User_Town")));  
    28.         selectTown.selectByVisibleText("浦东");  
    29.           
    30.         //这里只是想遍历一下下拉列表所有选项,用click进行选中选项  
    31.         Select selectCity = new Select(dr.findElement(By.id("User_City")));  
    32.         for(WebElement e : selectCity.getOptions())  
    33.             e.click();  
    34.     }  
    35.   
    36. }  
     

    从上面可以看出,对下拉框进行操作时首先要定位到这个下拉框,new 一个Selcet对象,然后对它进行操作。

  • 相关阅读:
    java中sleep()和wait()区别
    那些年遇到的坑--------“集合转数组”
    HashMap中推荐使用entrySet方式遍历Map类集合KV而不是keySet方式遍历
    java.util.ConcurrentModificationException 异常原因和解决方法
    java.lang.Exception: No tests found matching
    https和http的主要区别
    交换性别sql
    判断奇偶数
    Jmeter安装使用
    java.io.EOFException: Unexpected EOF read on the socket
  • 原文地址:https://www.cnblogs.com/yye2010/p/4596915.html
Copyright © 2011-2022 走看看