我需要从下拉列表中选择一个随机选项。我的理解是我需要计算可用选项的数量,然后在0和可用选项的数量之间选择一个随机索引。
到目前为止,我有这个 -
public static void selectRandomIndexDropdown(this IWebDriver driver, By elementName)
{
var element = driver.FindElement(elementName);
element.selectRandomIndexDropdown();
}
public static void selectRandomIndexDropdown(this IWebElement element)
{
if (element == null || element.TagName.ToLower() != "select")
return;
int indexCount = element.FindElements(By.TagName("option")).Count();
new SelectElement(element).SelectByIndex(Rnd.Next(0, indexCount));
}
试图称呼它 -
driver.selectRandomIndexDropdown(By.XPath("//*[@id='ASPxGridViewDeskFees_DXEFL_DXEditor1_I']"));
这似乎不起作用。没有显示错误或抛出的异常,看起来代码执行,但没有单击列表中的选项。有什么想法吗?
我正在使用java,但我敢肯定C#答案是相似的
我通常使用一种方法为我提供当前可用选项列表:
public static List<WebElement> getOptions(WebElement selectField) {
Select dropdown = new Select(selectField);
return dropdown.getOptions();
}
从那里,您在0和.size((之间选择一个随机数以获取一个值以传递到选择方法:
public static void selectOptionByIndex(WebElement selectField, int index) {
wait.until(ExpectedConditions.elementToBeClickable(selectField));
Select dropdown = new Select(selectField);
dropdown.selectByIndex(index);
}
或简单生成的randum x nuber从2到选项数,并找到这样的元素:
string myxpath = "//*[@id='select_id']/option[" + X + "]";
IWebElement element = driver.FindElement(By.XPath(myxpath));