首页 > 解决方案 > 访问表中的元素(Selenium,C#)

问题描述

我正在尝试自动化工作中的任务,这需要我访问嵌套表中的元素。我设法通过 Chrome 获取 XPath,但收到无法找到元素的错误。

错误信息: 在此处输入图像描述

标签: c#selenium

解决方案


不要使用来自 chrome 的绝对 xpath,因为这可能会失败。处理表时,最佳做法是访问 table>tr>td。以下是对您有帮助的示例。这可以是您的起点,然后您可以根据单元格文本单击该元素。

//find table.
WebElement mytable = driver.findElement(By.xpath("html/body/table/tbody"));

//find rows of table.
List < WebElement > rows_table = mytable.findElements(By.tagName("tr"));

//calculate no of rows In table.
int rows_count = rows_table.size();

//Loop will execute for all the rows of the table
for (int row = 0; row < rows_count; row++) {

//find columns(cells) of that specific row.
List < WebElement > Columns_row = rows_table.get(row).findElements(By.tagName("td"));
//calculate no of columns(cells) In that specific row.
int columns_count = Columns_row.size();
System.out.println("Number of cells In Row " + row + " are " + columns_count);

//Loop will execute till the last cell of that specific row.
for (int column = 0; column < columns_count; column++) {
    //To retrieve text from the cells.
    String celltext = Columns_row.get(column).getText();
    System.out.println("Cell Value Of row number " + row + " and column number " + column + " Is " + celltext);
}
}

推荐阅读