0

The list contains values that start with "Comm"+String. So "Comm" is common in front of every value in the dropdown list. I want to pick a random string from the list which starts with "Comm" I read the element using

var selectList = driver.FindElement(GroupDropdown_1); selectList.FindElement(By.XPath(string.Format("//option[starts-with(text(),'{0}')]", "Comm"))).Click();

But it always pick by default the first occurrence in the dropdown list list. The HTML code is

<div id="RPaffgroups" name="RPaffgroups" style="display:inline;"><select name="groupid">
<option value="0">Comm Group: No Member Commission Group   [ 52 mbrs]</option>
<option value="106">Aff Group: Retail - Affiliates 2018   [ 46 mbrs]</option>
<option value="106">Aff Group: Merchandise - Affiliates 2002   [ 433 mbrs]</option>
<option value="-1" selected="">Comm Group: Default Commission Group   [ 52 mbrs]</option>
<option value="22" selected="">Comm Group: 0 Comm Group   [ 52 mbrs]</option>
</select>&nbsp;&nbsp;<input type="checkbox" id="cbShowHiddenGroups" border="0" onclick="ToggleGroup('groupid',this);">Show hidden groups</div>

As seen above it always pick the first occurrence of the string starts with "Comm" which in the above case is Comm Group: No Member Commission Group [ 52 mbrs]

Norayr Sargsyan
  • 1,737
  • 1
  • 12
  • 26
Analyst
  • 105
  • 1
  • 9
  • Does this answer your question? [How do I generate a random int number?](https://stackoverflow.com/questions/2706500/how-do-i-generate-a-random-int-number) – Sinatr Nov 05 '20 at 14:03
  • No as this is to get random from a list but the problem i am facing is that there are certain values in string which does not starts with "comm" and there it is failing when clicking those strings and the value= in the list generated randomly – Analyst Nov 05 '20 at 14:10

1 Answers1

1

The reason why FindElement() is picking the first value of matching xpath is because it implements FindElements() (which selects first if any results have been found). So the workaround here will be to get all elements by following xpath and select random.

selectList.FindElements(xpath).ToList().OrderBy(x => Guid.NewGuid()).First();
mjagic
  • 45
  • 1
  • 9