Selenium Webdriver Java:如何使用行号和列号单击表中的特定单元格
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/37598041/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Selenium Webdriver Java: How to click on a particular cell in table using row and column numbers
提问by amateurCoder
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("Hymanson")){
System.out.println("Hymanson is present in the table");
}else{
System.out.println("Hymanson is not available in the table");
}
Thread.sleep(10000);
driver.quit();
}
}
回答by ddavison
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("Hymanson"))
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. If it has a link in the TD, then you can do something like:
但请记住,单击<td>
可能不会实际触发,因为<td>
可能不会侦听单击事件。如果它在 TD 中有链接,那么您可以执行以下操作:
Cell.findElement("a").click();
回答by Srikanth Rao
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));