C# 和 Selenium:使用下拉列表选择ByText

本文关键字:下拉列表 选择 ByText Selenium | 更新日期: 2023-09-27 18:37:18

我有一个无法从 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

C# 和 Selenium:使用下拉列表选择ByText

错误消息几乎告诉你你需要的一切。

  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
}