我是 Selenium 的新手,希望有人能帮助我。我试图找到表格中的特定单元格并返回其文本内容。该表由下面的 html
表示:
<h2>Test #2</h2>
<table border="1">
<tbody>
<tr>
<td>1:1</td>
<td>1:2</td>
<td>1:3</td>
</tr>
<tr>
<td>2:1</td>
<td>2:2</td>
<td>2:3</td>
</tr>
<tr>
<td>3:1</td>
<td>3:2</td>
<td>3:3</td>
</tr>
</tbody>
</table>
</div>
我正在尝试使用 3:2 从单元格返回文本。我需要改变什么才能实现这一点?
这是我到目前为止所拥有的:
public void test2() throws InterruptedException {
getValue(1, 3);
}
public void getValue(int row, int col) {
List<WebElement> tableRows = driver.findElements(By.cssSelector("#req2 table tbody tr"));
List<WebElement> tableCol = tableRows.get(row - 1).findElements(By.tagName("td"));
System.err.println(tableCol.get(col - 1).getText());
}
最佳答案
使用以下CssSelector
tbody>tr:nth-child(3)>td:nth-child(2)
nth-child()
函数使您可以灵活地轻松找到具有不同索引
的子项
我强烈建议您将其与某种显式
等待一起使用,以正确定位元素
By css = By.cssSelector("tbody>tr:nth-child(3)>td:nth-child(2)");
WebElement myDynamicElement = (new WebDriverWait(driver, 10))
.until(ExpectedConditions.presenceOfElementLocated(css));
System.out.println(myDynamicElement.getText());
打印
3:2
代码稍作更改,如下所示
@Test
public void DemoTest() throws InterruptedException {
System.out.println(test2());
}
public String test2() throws InterruptedException {
return getValue(3, 2).getText() ;
}
public WebElement getValue(int row, int col) {
By css = By.cssSelector("tbody>tr:nth-child(" + row + ")>td:nth-child(" + col + ")");
WebElement myDynamicElement = (new WebDriverWait(driver, 10))
.until(ExpectedConditions.visibilityOfElementLocated(css));
return myDynamicElement;
}
打印
3:2
关于java - Selenium,在表中定位单元格,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28620720/