Selenium Select - Selecting dropdown option by part of the text

前端 未结 8 1903
清歌不尽
清歌不尽 2020-12-19 16:57

The class Selenium Select has 3 methods of different option selection:

  1. selectByIndex
  2. selectByValue
  3. selectByVisibleText

Now,

8条回答
  •  醉话见心
    2020-12-19 17:26

    Eventually I combined the answers here and that's the result:

    Select select = new Select(driver.findElement(By.xpath("//whatever")));
    
    public void selectByPartOfVisibleText(String value) {
        List optionElements = driver.findElement(By.cssSelector("SELECT-SELECTOR")).findElements(By.tagName("option"));
    
        for (WebElement optionElement: optionElements) {
            if (optionElement.getText().contains(value)) {
                String optionIndex = optionElement.getAttribute("index");
                select.selectByIndex(Integer.parseInt(optionIndex));
                break;
            }
        }
    
        Thread.sleep(300);
    }
    

    And in Scala (need it eventually in Scala) it looks like:

      def selectByPartOfVisibleText(value: String) = {
        val optionElements: util.List[WebElement] = selectElement.findElements(By.tagName("option"))
    
        breakable {
          optionElements.foreach { elm =>
            if (elm.getText.contains(value)) {
              val optionIndex = elm.getAttribute("index")
              selectByIndex(optionIndex.toInt)
              break
            }
          }
        }
        Thread.sleep(300)
      }
    

提交回复
热议问题