• 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); }
  • 相关阅读:
    AcWing 1228. 油漆面积
    AcWing 1275. 最大数
    AcWing 245. 你能回答这些问题吗
    lightdb开启mysql兼容模式
    postgresql闪回查询及其问题
    postgresql中work_mem的实现及临时文件的实现
    postgresql/lightdb数据文件丢失和损坏恢复系统表
    LightDB 22.3与龙芯LoongArch完成认证适配
    论lightdb/postgresql中的search_path及实现兼容性管理
    rabbitmq问题清单
  • 原文地址:https://www.cnblogs.com/Shanghai-vame/p/7805939.html
Copyright © 2020-2023  润新知