我使用的代码可以通过可见文本从列表框中完美地选择项目。
var selectElement = new SelectElement(TestFramework.FindWebElement(this));
selectElement.SelectByText(text);
问题是我动态更改了项目中的文本。它可能像:
- item1 - 或 --- item1 ---
但我需要选择包含“item1”的文本的项目。有什么建议吗?
答案 0 :(得分:3)
查看来源,如果第一次搜索(直接SelectByText
匹配)没有返回任何内容,则应contains
方法搜索Equals
匹配项。如果它没有这样做,请使用Selenium Developer's引发错误并同时编写自己的扩展方法:
/// <summary>
/// Select an option by first searching for a case insensitive direct match then trying a case insenstive contains match.
/// </summary>
/// <param name="selectElement">The SelectElement to use.</param>
/// <param name="searchText">The text to find in the options.</param>
public static void SelectByText(this SelectElement selectElement, string searchText)
{
var allOptionsThatHaveText =
selectElement.Options.Where(se => se.Text.Equals(searchText, StringComparison.OrdinalIgnoreCase));
if (allOptionsThatHaveText.Any())
{
foreach (var option in allOptionsThatHaveText)
{
option.Click();
}
return;
}
var optionWithText = selectElement.Options.Where(option => option.Text.IndexOf(searchText, StringComparison.OrdinalIgnoreCase) >= 0);
if (optionWithText.Any())
{
foreach (var option in optionWithText)
{
option.Click();
}
return;
}
throw new NoSuchElementException(string.Format("Cannot find the text: {0} by either a case insenstive match or a case insensitive equals match.", searchText));
}
答案 1 :(得分:1)
您可以使用XPath而不是SelectByText,并在XPath中使用“contains”。
以下是一个例子:
var selectElement = new SelectElement(_driver.FindElement(By.XPath("//*[contains(text(), 'YOUTEXTHERE')]")));
答案 2 :(得分:0)
尝试使用以下代码: -
var option = new SelectElement(browser.FindElement(By.CssSelector("#Menu_ParentMenuID"))).SelectBySubText("item1");