Java Selenium Select - 按部分文本选择下拉选项

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/29772075/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-11 08:34:38  来源:igfitidea点击:

Selenium Select - Selecting dropdown option by part of the text

javaseleniumselenium-webdriverwebdriverselenium-chromedriver

提问by Johnny

The class Selenium Selecthas 3 methods of different option selection:

Selenium Select类有 3 种不同的选项选择方法:

  1. selectByIndex
  2. selectByValue
  3. selectByVisibleText
  1. 按索引选择
  2. 按值选择
  3. 选择可见文本

Now, I have a situation where I want to select an option by some text that partiallyappear in one of the options visible text (don't want to expose myself to changes in the WHOLE text).

现在,我有一种情况,我想通过一些文本选择一个选项,这些文本部分出现在一个选项可见文本中(不想让自己暴露在整个文本中的更改)。

For example:

例如:

<option value="0" label="not-intresting">VERY-LONG-TEXT-THAT-I-NEED-TO-SELECT-DOLLAR</option>

And i want to select this option only by providing the "DOLLAR", something like:

我只想通过提供“美元”来选择此选项,例如:

select.selectByPartOfVisibleText("DOLLAR") 

How would you implement it effectively?

你将如何有效地实施它?

采纳答案by Zach

You can try a logic like this hope this helps

您可以尝试这样的逻辑希望这会有所帮助

List <WebElements> optionsInnerText= driver.findElements(By.tagName("option"));
for(WebElement text: optionsInnerText){
    String textContent = text.getAttribute("textContent");
    if(textContent.toLowerCase.contains(expectedText.toLowerCase))
           select.selectByPartOfVisibleText(expectedText);
    }
}

回答by LittlePanda

Get a list of all the optionvalues and then check if the value contains your partial text. Something like this:

获取所有option值的列表,然后检查该值是否包含您的部分文本。像这样的东西:

List<WebElement> list = driver.findElements(By.tagName("option"));
Iterator<WebElement> i = list.iterator();
while(i.hasNext()) {
    WebElement wel = i.next();    
    if(wel.getText().contains("your partial text"))
    {
       //select this option
    }
} 

回答by Johnny

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<WebElement> 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:

Scala 中(最终在 Scala 中需要它)它看起来像:

  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)
  }

回答by johnkerry

This is what I used to solve the issue in python.

这就是我用来解决python中的问题的方法。

I used this option, so it selects the text that uses the word DOLLARinstead of typing the whole word as the value.

我使用了这个选项,所以它选择使用这个词的文本DOLLAR而不是输入整个词作为值。

Select(driver.find_element_by_name(ELEMENT)).select_by_value("DOLLAR")

instead of

代替

Select(driver.find_element_by_name(ELEMENT)).select_by_visible_text(text)

回答by Cash_m

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.

我的解决方案是使用 xpath 来查找作为选择子项的选项。可以使用任何 xpath 方法来查找选择;在这个例子中,我找到了 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:

经过更多思考,我意识到可以完全使用 xpath 找到该选项:

driver.findElements(By.xpath("//select[@id = 'selectId')]/option[contains(text(), 'DOLLAR')]")).click();

回答by Saikat

Using Java 8 Stream/Lambda:

使用 Java 8 Stream/Lambda:

protected void selectOptionByPartText(WebElement elementAttr, String partialText) {
        Select select = new Select(elementAttr);
        select.getOptions().parallelStream().filter(option -> option.getAttribute("textContent").toLowerCase().contains(partialText.toLowerCase()))
                .findFirst().ifPresent(option -> select.selectByVisibleText(option.getAttribute("textContent")));
    }

回答by NarendraR

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

在最新的 Selenium 3.x 或 4.x 版本中,Select 类可用于从下拉列表中选择一个选项。

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

例如:有一个风味下拉列表,需要选择包含名称为的风味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);
    }
}