zoukankan      html  css  js  c++  java
  • 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); }
  • 相关阅读:
    repo manifest xml 文件修改后提交命令
    linux下i2c驱动笔记 转
    这么多年至今今天遇到的一件令我气愤还无法想象的,希望看到的人引以为戒吧。不明白现在的孩子怎么了!
    GitLab 之 Linux十分钟快装
    Mongodb For Mac OSX && 登录验证
    Grunt 5分钟上手:合并+压缩前端代码
    回顾:前端模块化和AMD、CMD规范(全)
    通过NPM快速发布你的NodeJS模块(组件包)
    【linux】netlink
    【Java基础知识】JNI入门
  • 原文地址:https://www.cnblogs.com/Shanghai-vame/p/7805939.html
Copyright © 2011-2022 走看看