我正在尝试根据单元格索引和行标识符获取表格单元格的文本。在下面的示例表中,我想将单元格的文本与单元格“text6”放在同一行中。这是我正在处理的表的一个示例:
<table cellspacing="0" cellpadding="0" class="fixedTable" id="PackageTable_dataTable" style="width: 1262px;">
<tbody class="tableData" id="PackageTable_dataBody">
<tr height="24px" uid="section1" index="0" class="alternateRow">
<td><div style="overflow: hidden; width: 193px;"><span title="text1">text1</span></div></td>
<td><div style="overflow: hidden; width: 57px;"><span title="text2">text2</span></div></td>
<td><div style="overflow: hidden; width: 115px;"><span title="text3">text3</span></div></td>
</tr>
<tr height="24px" uid="section2" index="1" class="alternateRow">
<td><div style="overflow: hidden; width: 193px;"><span title="text4">text4</span></div></td>
<td><div style="overflow: hidden; width: 57px;"><span title="text5">text5</span></div></td>
<td><div style="overflow: hidden; width: 115px;"><span title="text6">text6</span></div></td>
</tr>
<tr height="24px" uid="section3" index="2" class="alternateRow">
<td><div style="overflow: hidden; width: 193px;"><span title="text7">text7</span></div></td>
<td><div style="overflow: hidden; width: 57px;"><span title="text8">text8</span></div></td>
<td><div style="overflow: hidden; width: 115px;"><span title="text9">text9</span></div></td>
</tr>
</tbody>
</table>
这是我的非工作代码:
public static string returnTableCellValue(string TableID, string TableRowIdentifier, int targetCellIndex)
{
string cellValue = string.Empty;
try
{
IWebElement baseTable = Global.driver.FindElement(By.Id(TableID));
// gets all table rows
ICollection<IWebElement> rows = baseTable.FindElements(By.TagName("tr"));
// for every row
foreach (IWebElement row in rows)
{
if (row.FindElement(By.XPath("//span[text()='" + TableRowIdentifier + "']")).Displayed)
{
Global.log.WriteLine("row identifier found!");
IWebElement key = row.FindElement(By.XPath("//td[" + targetCellIndex + "]"));
IWebElement keySpan = key.FindElement(By.TagName("span"));
cellValue = keySpan.Text;
}
}
return cellValue;
}
catch (Exception ex)
{
Global.log.WriteLine("returnTableCellValue exception: " + ex.ToString());
return string.Empty;
}
}
知道怎么做吗?
答案 0 :(得分:3)
代码中的以下行会在NoSuchElementException
找不到具有匹配条件的元素的第一行上抛出FindElement
。
if (row.FindElement(By.XPath("//span[text()='" + tableRowIdentifier + "']")).Displayed)
改为使用FindElements(),如下所示:
IWebElement matchedRow = null;
try
{
foreach(var row in rows)
{
if(row.FindElements(By.XPath("td/span")).FirstOrDefault(cell => cell.Text.Trim().Equals(TableRowIdentifier)) != null)
{
matchedRow = row;
break;
}
}
}
catch (NoSuchElementException)
{
//couldnot find
matchedRow = null;
}
if(matchedRow !=null)
{
cellValue = matchedRow.FindElement(By.XPath(string.Format("td[{0}]/span",targetCellIndex)).Text;
}
return cellValue;