c# - 如何通过 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()
解决方案
试试这个:
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();
}
推荐阅读
- java - 在类路径上有多个 servlet-api 库时出错
- javascript - 在 d3 库中的可缩放圆包图中添加边
- php - 如何删除字符串中两行之间的特定换行符而不删除其他换行符?php
- javascript - Nuxt 来自 api 的动态路由
- apache-kafka - 使用 localstack 测试 kafka 应用程序
- validation - wxPython 对话框:如何验证多个控件中的输入?
- javascript - primeng p-treeTableToggler 图标已更改,而不是原来的 pi pi-fw pi-chevron-right 图标
- pandas - 如何根据检查列中是否存在值的条件将行添加到 DF
- vue.js - 无法让 v-img 在 v-flex 内居中
- lua - 将字符串与函数 Lua 关联