[英]Selenium Webdriver Java: How to click on a particular cell in table using row and column numbers
I have written a code to verify if a given text is present in that row or not but how do i click in a particular cell?我已经编写了一个代码来验证该行中是否存在给定的文本,但是如何单击特定单元格? Please help me.请帮帮我。
Below is the code i have written for verifying the text.下面是我为验证文本而编写的代码。
package com.Tables;
import java.util.List;
public class HandlingTables {
public static void main(String[] args) throws InterruptedException {
String s="";
System.setProperty("webdriver.chrome.driver", "D:/chromedriver.exe");
WebDriver driver = new ChromeDriver();
driver.get("http://www.w3schools.com/html/html_tables.asp");
WebElement table = driver.findElement(By.className("w3-table-all"));
List<WebElement> allrows = table.findElements(By.tagName("tr"));
List<WebElement> allcols = table.findElements(By.tagName("td"));
System.out.println("Number of rows in the table "+allrows.size());
System.out.println("Number of columns in the table "+allcols.size());
for(WebElement row: allrows){
List<WebElement> Cells = row.findElements(By.tagName("td"));
for(WebElement Cell:Cells){
s = s.concat(Cell.getText());
}
}
System.out.println(s);
if(s.contains("Jackson")){
System.out.println("Jackson is present in the table");
}else{
System.out.println("Jackson is not available in the table");
}
Thread.sleep(10000);
driver.quit();
}
}
You could modify your loop to click, instead of contat'ing a giant string你可以修改你的循环点击,而不是 contat'ing 一个巨大的字符串
for(WebElement row: allrows){
List<WebElement> Cells = row.findElements(By.tagName("td"));
for(WebElement Cell:Cells){
if (Cell.getText().contains("Jackson"))
Cell.click();
}
}
Keep in mind though, that clicking the <td>
may not actually trigger as the <td>
may not be listening for the click event.但请记住,单击<td>
可能实际上不会触发,因为<td>
可能不会侦听单击事件。 If it has a link in the TD, then you can do something like:如果它在 TD 中有链接,那么您可以执行以下操作:
Cell.findElement("a").click();
You will have to build a dynamic selector to achieve this.您必须构建一个动态选择器来实现这一点。
For example:例如:
private String rowRootSelector = "tr";
private String specificCellRoot = rowRootSelector + ":nth-of-type(%d) > td:nth-of-type(%d)";
And in the method where you take Row and Column as input parameter, the selector has to be built.而在以 Row 和 Column 作为输入参数的方法中,必须构建选择器。
String selector = String.format(specificCellRoot, rowIndex, columnIndex);
And, now you can click or do any other operation on that web element.而且,现在您可以在该 Web 元素上单击或执行任何其他操作。
driver.findElement(By.cssSelector(selector));
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.