I am writing a WebDriver test case in C# where I need to select an item in a drop down list.
The text on the dropdown will be a persons name followed by distance and capacity. The problem is that only the first section of the text displayed is known at runtime, ie the persons name. If this were a link I could click on it using the following fairly standard code:
driver.FindElements(By.Id("Name")).Click();
But alas it is not a link. I have copied the definition of the SelectByText()
method from SelectElement
class in OpenQA.Selenium.Support.UI
below. Or more specifically the comments from the definition relating to substring/partial text matches in the SelectByText()
method:
// Parameters:
// text:
// The text of the option to be selected. If an exact match is not found, this
// method will perform a substring match.
I can't get the method to perform a substring match
.
This is what I have tried. For example my HTML code is similar to this:
<select id="ddlTest">
<option>Firstname Lastname - 35 miles - 50%</option>
</select>
I have tried the following C# Webdriver which didn't find the substring match I was expecting.
var selectList = driver.FindElement(By.Id("ddlTest"));
var options = new SelectElement(selectList);
options.SelectByText("Firstname Lastname");
And that is where the test fails as it couldn't find an element with the text Firstname Lastname
.
How do I get this method to use the substring match it describes in the definition comments I copied above?
selectList.FindElement(By.XPath(string.Format("./option[starts-with(text(), '{0}')]", "Firstname Lastname"))).Click();
Not tested but should work for you
By byXpath = By.XPath("//select[@id='ddlTest']/option[contains(text(),'Firstname Lastname')]");
driver.FindElement(byXpath).Click();
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.