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); }
  • 相关阅读:
    JavaScript对象与JSON字符串的相互转换
    IE6下javascript:void(0)不可用的解决
    mybatis-spring集成:配置多数据库源中遇到的问题
    网易免费企业邮箱Foxmail设置方法
    ARM Linux 驱动Input子系统之按键驱动测试
    arm Linux 驱动LED子系统 测试
    AM335x内核模块驱动之LED
    ARM开发板搭建NFS网络文件共享方法
    AM335x开发板与PC机虚拟机建立tftp文件传输
    am335xSD卡启动--文件系统制作
  • 原文地址:https://www.cnblogs.com/Shanghai-vame/p/7805939.html
Copyright © 2011-2022 走看看