首页 > 解决方案 > 如何通过 element.findElements[n].findElement() 查找表格的内部元素

问题描述

对于下面的 HTML 代码

<table class="table" id="Table1" xpath="1">
   <thead>
      <tr class="table-header">      </tr>
   </thead>
   <tbody>
      <tr class="table-row">
         <span><i data-icon="" class="icon fa fa-pencil fa-1x" id="l2_0-0-Edit_Icon"></i></span>
      </tr>
      <tr class="table-row">
         <span><i data-icon="" class="icon fa fa-pencil fa-1x" id="l2_0-0-Edit_Icon"></i></span>
      </tr>
      <tr class="table-row">
         <span><i data-icon="" class="icon fa fa-pencil fa-1x" id="l2_0-0-Edit_Icon"></i></span>
      </tr>
      <tr class="table-row">
         <span><i data-icon="" class="icon fa fa-pencil fa-1x" id="l2_0-0-Edit_Icon"></i></span>
      </tr>
      <tr class="table-row">
         <span><i data-icon="" class="icon fa fa-pencil fa-1x" id="l2_0-0-Edit_Icon"></i></span>
      </tr>
   </tbody>
</table>
<pre>

假设我需要单击第 4 行的编辑按钮。我可以使用以下代码。(此代码工作正常)

Driver.FindElement(By.XPath("//table[@id='Table1']//tr[3]//i[contains(@id,'Edit_Icon')]")).Click()

问题是编辑按钮可能并不总是存在于第 1、第 2 或第 3 行。(其动态基于差异条件)

<table class="table" id="Table1" xpath="1">
   <thead>
      <tr class="table-header">      </tr>
   </thead>
   <tbody>
      <tr class="table-row">
         <span><i data-icon="" class="icon fa fa-pencil fa-1x" id="l2_0-0-Edit_Icon"></i></span>
      </tr>
      <tr class="table-row">
         
      </tr>
      <tr class="table-row">
         <span><i data-icon="" class="icon fa fa-pencil fa-1x" id="l2_0-0-Edit_Icon"></i></span>
      </tr>
      <tr class="table-row">
         <span><i data-icon="" class="icon fa fa-pencil fa-1x" id="l2_0-0-Edit_Icon"></i></span>
      </tr>
      <tr class="table-row">
         
      </tr>
   </tbody>
</table>

因此,我尝试遵循以下代码,然后根据需要更改“3”。(我想做的是找到 3row 并在其中我试图找到编辑图标)。但它不起作用。

我如何编写一个总是单击我想要的行的 Xpath,而不管其他行是否有“编辑”按钮?

Driver.FindElement(By.XPath("//table[@id='Table1']")).FindElements(By.XPath("//tr"))[3].FindElement(By.XPath("//i[contains(@id,'Edit_Icon')]")).Click()

标签: c#selenium-webdriverxpathfindelement

解决方案


试试这个:

Driver.FindElement(By.XPath("//table[@id='Table1']")).FindElements(By.XPath(".//tr"))[3].FindElement(By.XPath(".//i[contains(@id,'Edit_Icon')]")).Click();

我不能保证表格内会有 3 个tr元素。
正如您所提到的,该元素可能不包含编辑图标,但这将找到正确的元素。
如果您希望在单击之前检查该元素是否存在,您可以执行以下操作:

var list = Driver.FindElement(By.XPath("//table[@id='Table1']")).FindElements(By.XPath(".//tr"))[3].FindElements(By.XPath(".//i[contains(@id,'Edit_Icon')]"));
if(list.Count()>0){
    list[0].Click();
    }

推荐阅读