C# 和 selenium:使用下拉列表的 selectByText

C# and selenium: selectByText using a dropdownlist

我有一个无法从 selectByText 调用的元素列表。如果我使用 "Test1" 而不是 dropdownLists[i],代码可以工作,但是我想遍历 10 个项目的列表

代码:

static void dropdownLists()
{
    dropdownList = new List<string>();
    dropdownList.Add("Test1");
    dropdownList.Add("Test2");
    dropdownList.Add("Test3");                
}

//在for循环中使用

for (int i = 0; i < dropdownList.Count; i++)
{
       System.Console.WriteLine("dropdownList: {0}", dropdownList[i]);
       new SelectElement(driver.FindElement(By.Id("DocumentType")))
       .SelectByText(dropdownLists[i]);
       Screenshot ss = ((ITakesScreenshot)driver).GetScreenshot();
}

我收到的错误是:

错误 2 参数 1:无法从 'method group' 转换为 'string' C:\myCSharp\mySelenium\mySelenium\ProgramCRM1.cs 76 91 myInfoCenter

错误 3 无法将带 [] 的索引应用于 'method group' 类型的表达式 C:\myCSharp\mySelenium\mySelenium\ProgramCRM1.cs 76 91 myInfoCenter

错误 1 ​​'OpenQA.Selenium.Support.UI.SelectElement.SelectByText(string)' 的最佳重载方法匹配有一些无效参数 C:\myCSharp\mySelenium\mySelenium\ProgramCRM1.cs 76 17 myInfoCenter

错误消息几乎告诉了您所需的一切。

  1. 'OpenQA.Selenium.Support.UI.SelectElement.SelectByText(string)' has some invalid arguments。所以你没有将字符串传递给方法。

  2. Error 3 Cannot apply indexing with [] to an expression of type 'method group'。什么? [] 不能应用于 dropdownLists?为什么?

  3. Error 2 Argument 1: cannot convert from 'method group' to 'string'。哦,那是因为dropdownLists是函数名,不是变量!

现在你应该知道你的错误了:你使用了函数名 dropdownLists 而不是变量名 dropdownList.

顺便说一句,尝试更好地命名您的函数。通常在开头加上一个动词会使事情更清楚。例如,getDropdownListpopulateDropdownList.

在这种情况下更容易做的事情是SelectByIndex(i)我猜你把实施复杂化了

如果你想坚持你的计划,我想以下也是更好的选择:

var selectElement = new SelectElement(Driver.FindElement(By.Id("DocumentType")));
int options = selectElement.Options.Count;

for (int i = 0; i < options; i++)
{
    Console.WriteLine(selectElement.Options[i].Text);
}

编辑

满足OP的标准

By byXpath = By.XPath("//select[@id='DocumentType']");

//wait for the element to exist
new WebDriverWait(Driver, TimeSpan.FromSeconds(10)).Until(ExpectedConditions.ElementExists(byXpath));

IWebElement element = Driver.FindElement(byXpath);
var selectElement = new SelectElement(element);
int options = selectElement.Options.Count;

for (int i = 0; i < options; i++)
{
    Console.WriteLine(selectElement.Options[i].Text);

    //in case if other options refreshes the DOM and throws StaleElement reference exception
    new SelectElement(Driver.FindElement(byXpath)).SelectByIndex(i);

    //do the rest of the stuff
}