Java+selenium 如何定位下拉框select

场景:需要进行下拉选择定位元素。

  一、select菜单

      select也是比较常见的,selenium封装了以下方法, 创建select

WebElement selector = driver.findElement(By.id("Selector")); //Selector 表示定位的元素
Select select = new Select(selector);

选择select的option有以下三种方法

selectByIndex(int index) 通过index
selectByVisibleText(String text) 通过匹配到的可见字符
selectByValue(String value) 通过匹配到标签里的value
 
二、示例:
selectByVisibleText(String text),text值就是页面下拉框肉眼看到的选项,例如:selectByValue(String value)  value就是select下面的一个个option标签的value值,通过抓取元素可见

备注:

另外还有一个新手很容易出错的地方,不要看到下拉选择框就认为可以使用select,表示根据公司目前现在的情况看,有些下拉选择框不都是使用select的!!先抓取选择框看下是不是select标签的。
 
 

 三、关键代码示例:

 WebElement selector = waitFor(By.xpath("//select[@id='0']"));
 Select sel = new Select(selector);
 sel.selectByVisibleText(leaveType);

四、优化代码:

//优化前
    WebElement selector = driver.findElement(By.xpath("//select[contains(@data-bind,'AuditType')]"));
        Select sel = new Select(selector);
        sel.selectByVisibleText(auditType);


//优化后
        selectByVisibleText(By.xpath("//select[contains(@data-bind,'AuditType')]"), auditType);

五: 调用方法

1  public void selectByVisibleText(By by, String text) {
2         Select sel = new Select(waitForShort(by));
3         sel.selectByVisibleText(text);
4     }

六 : 如何随机循环选择下拉框取值。

    public void selectByRandomVisbleText(By by) {
        Select sel = new Select(waitForShort(by));
        //getOptions方法获取 WebElement得集合
        List<WebElement> webEletments = sel.getOptions();
        //新建List存储文本值
        List<String> downs = new ArrayList<String>();
        //循环webElement集合,将每个选项添加到List集合中。
        for (WebElement webElement: webEletments) {
            downs.add(webElement.getText());
       System.out.println("下拉值" +webElement.getText()); }
//获取下拉值数据 int num = webEletments.size(); int random = Utils.getRandInt(0, num - 1); //根据随机数选择 sel.selectByIndex(random); }
原文地址:https://www.cnblogs.com/Shanghai-vame/p/7805939.html