[英]Select a dropdown element with dynamic ID using Webdriver, C#
我有一种情况要解决。 我正在使用Webdriver,C#。 当我尝试使用CSSSelector时,它只是将参数读取为字符串。 请仔细查看。这是HTML。
<div class="select2-container select2" id="s2id_UserRole" style="width: 100%;">
<a href="javascript:void(0)" class="select2-choice" tabindex="-1">
***<span class="select2-chosen" id="select2-chosen-7"> </span>***
<abbr class="select2-search-choice-close"></abbr>
<span class="select2-arrow" role="presentation">
<b role="presentation"></b></span></a><label for="s2id_autogen7" class="select2-offscreen"></label>
<input class="select2-focusser select2-offscreen" type="text" aria-haspopup="true" role="button" aria-labelledby="select2-chosen-7" id="s2id_autogen7">
<div class="select2-drop select2-display-none select2-with-searchbox">
<div class="select2-search">
<label for="s2id_autogen7_search" class="select2-offscreen"></label>
<input type="text" autocomplete="off" autocorrect="off" autocapitalize="off" spellcheck="false" class="select2-input" role="combobox" aria-expanded="true" aria-autocomplete="list" aria-owns="select2-results-7" id="s2id_autogen7_search" placeholder="">
</div>
<ul class="select2-results" role="listbox" id="select2-results-7"> </ul></div>
</div>
我要获取ID的元素是带有这种ID的下拉列表: id="select2-chosen-7"
。 “ select-chosen-”是静态的,数字部分是动态的。 阅读论坛后,所有建议似乎都没有答案。 最后,这是我正在使用的代码,但仍然无法正常工作-
IWebElement DropDownPath = driver.FindElement(By.CssSelector("*[id^='select2-chosen-'][id*='select2-chosen-']"));
SelectElement DropDown = new SelectElement(DropDownPath);
DropDown.SelectByText(UserConstants.UserRoleText);
您应该使用递归:
public void ConutNumber(int count)
{
...
GoThroughElements(count);
...
}
public void GoThroughElements(int count, List<String> recurseValues = new List<String>())
{
foreach(String value in ValuesAdd1)
{
recurseValues.Add(value);
if(count == 1)
{
// In deepest recursion iterate through the line of values
foreach(String i in recurseValues)
Console.WriteLine(i);
}
else if(count > 1)
{
GoThroughElements(--count, recurseValues);
}
else
{
throw new Exception("Wrong count!");
}
}
}
不要忘记检查您的计数是否包含无效值。 谨慎使用递归,如果不注意错误情况,很容易导致内存问题。
如果不需要将ValuesAddX分开,则可以有一个数组数组,然后遍历该数组:
public static string[][] ValuesAdd =
{
new [] { "a", "b", "c" },
new [] { "1", "2", "3" },
new [] { "x", "y", "z" },
};
public void NestedForeach()
{
// Note that count isn't required anymore as we're using
// ValuesAdd.Length as the count
NestedForeachRecursive(string.Empty, 0);
}
public void NestedForeachRecursive(string prefix, int depth)
{
foreach (var item in ValuesAdd[depth])
{
var nextDepth = depth + 1;
var nextPrefix = prefix + item;
if (nextDepth < ValuesAdd.Length)
NestedForeachRecursive(nextPrefix, nextDepth);
else
Console.WriteLine(nextPrefix);
}
}
请注意,因为您要遍历每个其他项目,所以此项目的性能将非常差。
该示例的输出为:
a1x
a1y
a1z
a2x
a2y
a2z
a3x
a3y
a3z
b1x
b1y
b1z
b2x
... and so on
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.