我是硒的新手,希望有人可以帮助我。我正在尝试在表中找到特定的单元格并返回其文本内容。该表由下面的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());
}
答案 0 :(得分:1)
使用以下CssSeleector
tbody>tr:nth-child(3)>td:nth-child(2)
nth-child()
功能可让您轻松找到具有不同index
我强烈建议您使用某种explicit
等待正确定位元素
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