我有一个无法从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:无法从“方法组”转换为“字符串” C:\ myCSharp \ mySelenium \ mySelenium \ ProgramCRM1.cs 76 91 myInfoCenter

错误3无法将带有[]的索引应用于类型为“方法组”的表达式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

最佳答案

在这种情况下,最容易做的事情是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
}

关于c# - C#和 Selenium :使用下拉列表选择selectByText,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/27908199/

10-10 17:18