Skip to main content
 首页 » 编程设计

c#之使用 selenium webdriver 和 C# 在 HTML 表格单元格中进行下拉选择

2024年01月01日46webabcd

我的 HTML 表格在第 5 列有一个单元格,其中包含值“1”、“2”和“3”的下拉菜单;

到目前为止,我已经可以到达那个单元格了:

ICollection<IWebElement> table = driver.FindElements(By.Id("highVolumeSearchResults_group")); 
List<IWebElement> elements = table.ToList();                 
ICollection<IWebElement> cell_action = driver.FindElements(By.XPath(".//tbody/tr/td[5]")); 

Cell_action - 是一个包含下拉选项/值“1”、“2”、“3”)的变量。我不确定如何继续,但我需要能够从下拉菜单中选择任何值。
谁能给我一个提示?

背后的代码:

 </table> 
      <table id="highVolumeSearchResults_group" class="highVolumeSearchResults"> 
      <thead> 
      <tbody> 
        <tr> 
         <td class="title letter" rowspan="1">W</td> 
         <td> 
            <a id="group-name-244" href="/Portal/Workgroup/Details?id=244">WorkGroup_Cats</a> 
         </td> 
         <td>0</td> 
         <td>12/28/2012 4:14:01 PM</td> 
         <td> 
           <select id="244" onchange="CommitAction(244, this.options[this.selectedIndex].value, this)"> 
              <option value="">------</option> 
              <option value="edit">Edit Users</option> 
              <option value="rename">Rename</option> 
              <option value="delete">Delete</option> 
           </select> 
        </td> 
      </tr> 
 </tbody> 
 </table> 

问题是“select id="244"”部分是动态生成的,所以我不应该使用这个 id。我需要想出 DropdownBox 选项,但还不知道怎么做。我也尝试继续:

IWebElement cell_action1 = cell_action.First(); and then  
SelectElement DropDownBox_action =  
    new SelectElement(cell_action1.FindElement( 
        By.XPath("//select[contains(, 'CommitAction')]")));   

这对我不起作用。

请您参考如下方法:

使用 SelectElement这实际上很简单:

var dropdown = driver.FindElement(By.XPath(".//tbody/tr/td[5]/select")); 
 
var selectElement = new SelectElement(dropdown); 
 
selectElement.SelectByValue("rename"); // or another value (ex: edit, delete) 

更新

如果你想得到<select>包含字符串 "CommitAction" 的元素在onchange属性,请使用此 XPath 表达式:"//select[contains(@onchange, 'CommitAction')]"