Reputation: 335
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
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
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
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
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
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