WebDriver C# - 使用部分文本从下拉列表中选择项目

时间:2015-02-02 18:01:41

标签: c# webdriver

我正在C#中编写一个WebDriver测试用例,我需要在下拉列表中选择一个项目。

下拉列表中的文字将是人名,后跟距离和容量。问题是只有所显示文本的第一部分在运行时是已知的,即人名。如果这是一个链接,我可以使用以下相当标准的代码点击它:

driver.FindElements(By.Id("Name")).Click();

但唉,这不是一个链接。我在SelectByText()下面的SelectElement类中复制了OpenQA.Selenium.Support.UI方法的定义。或者更具体地说,SelectByText()方法中与子字符串/部分文本匹配的定义中的注释:

// Parameters:
//   text:
//     The text of the option to be selected. If an exact match is not found, this
//     method will perform a substring match.

我无法将方法转到perform a substring match

这是我尝试过的。例如,我的HTML代码与此类似:

<select id="ddlTest">
   <option>Firstname Lastname - 35 miles - 50%</option>
</select>

我尝试过以下C#Webdriver,它找不到我期待的子串匹配。

var selectList = driver.FindElement(By.Id("ddlTest"));
var options = new SelectElement(selectList);
options.SelectByText("Firstname Lastname");

这是测试失败的地方,因为找不到包含文本Firstname Lastname的元素。

如何使用此方法来使用我在上面复制的定义注释中描述的子字符串匹配?

2 个答案:

答案 0 :(得分:2)

selectList.FindElement(By.XPath(string.Format("./option[starts-with(text(), '{0}')]", "Firstname Lastname"))).Click();

答案 1 :(得分:2)

未经测试但应该适合您

By byXpath = By.XPath("//select[@id='ddlTest']/option[contains(text(),'Firstname Lastname')]");
driver.FindElement(byXpath).Click();
相关问题