Selenium Select - Selecting dropdown option by part of the text

前端 未结 8 1861
清歌不尽
清歌不尽 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:29

    In latest Selenium version 3.x or 4.x, Select class can be used to select an option from dropdown.

    For example: There is a flavour dropdown where it require to select a flavour which contain name as Vanilla.

    WebElement flavour = driver.findElement(By.id("attribute178"));
    Select select = new Select(flavour);
    String expectedFlavourName = "Vanilla";
    List<WebElement> allFlavourList = select.getOptions();
    for (WebElement option : allFlavourList) {
        String currentFlavourName = option.getText();
        if (currentFlavourName.contains(expectedFlavourName)) {
            select.selectByVisibleText(currentFlavourName);
        }
    }
    
    0 讨论(0)
  • 2020-12-19 17:40

    My solution is to use xpath to find options that are children of the select. Any xpath method can be used to find the select; in this example I am finding the select by id.

    List<WebElement> options = driver.findElements(By.xpath("//select[@id = 'selectId')]/option"));
    
    for (WebElement option : options) {
        if (option.getText().contains("DOLLAR")) {
            option.click();
            break;
        }
    }
    

    After a little more thought I realize the option can be found entirely with xpath:

    driver.findElements(By.xpath("//select[@id = 'selectId')]/option[contains(text(), 'DOLLAR')]")).click();
    
    0 讨论(0)
提交回复
热议问题