user2365105
user2365105

Reputation: 335

How to select an option from dropdown list by matching text pattern using selenium webdriver and java

I'm trying to select an option from a dropdown list by matching only some part of visible text, since the whole text is not going to always be the same. Can anyone please help me out on this?

Upvotes: 1

Views: 11340

Answers (5)

Andrey Zakharov
Andrey Zakharov

Reputation: 91

C# with LINQ

var menuOptions = new SelectElement(Driver.FindElement({LocatorForMenu})).Options;
var requiredOption = menuOptions.FirstOrDefault(element => element.Text.Contains(partialTextToMatch));
if (requiredOption == null)
    throw new Exception("Wasn't able to select menu item: " + partialTextToMatch);
requiredOption.Click();

Upvotes: 1

MaewBot
MaewBot

Reputation: 66

Here is a java code for this

    WebElement dropdown = driverObj.findElement(By.id(id));
    dropdown.click();

    List<WebElement> options = dropdown.findElements(By.tagName("option"));
    for(WebElement option : options){
        String optTxt = option.getText();
        if(optTxt.contains(partialText)){
            option.click();
            break;
        }
    }
}

Upvotes: 0

confusified
confusified

Reputation: 2330

Perhaps this will work?

new Select(driver.findElement(By.id("MyIdOrOtherSelector"))).selectByVisibleText("Something");

Though I'm not sure if that will allow partial text. There is also

selectByValue(value)
selectByIndex(index)

If they are any use

Upvotes: 0

ragamufin
ragamufin

Reputation: 4162

I haven't tested this but here's how you would do it in C#, you should be able to transpose this quite easily into Java code. Two ways I can think of:

1)

string selBoxID = "id of select box";
string partialText = "option text to match";
driver.FindElement(By.XPath("//select[@id='" + selBoxID + "']/option[contains(text(), '" + partialText + "')]")).Click();

OR

2)

SelectElement elSel = new SelectElement(driver.FindElement(By.Id("id of select box")));
IList<IWebElement> opts = elSel.Options;
foreach (IWebElement elOpt in opts)
{
    if(elOpt.Text.Contains("partial text to look for"){
        elOpt.Click();
        return true;
    }
}
return false;

Upvotes: 3

HemChe
HemChe

Reputation: 2337

you can use the below command. Let me know if it is working.

driver.findElement(By.id("id of the dropdown")).sendkeys("part of visible text");
driver.findElement(By.id("id of the dropdown")).sendKeys(Keys.ENTER);

Upvotes: -1

Related Questions