![](/img/trans.png)
[英]How to click on the aside / previous Table Cell (TD) in the same row using Selenium Webdriver with Java?
[英]Selenium Webdriver Java: How to click on a particular cell in table using row and column numbers
我已經編寫了一個代碼來驗證該行中是否存在給定的文本,但是如何單擊特定單元格? 請幫幫我。
下面是我為驗證文本而編寫的代碼。
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();
}
}
你可以修改你的循環點擊,而不是 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();
}
}
但請記住,單擊<td>
可能實際上不會觸發,因為<td>
可能不會偵聽單擊事件。 如果它在 TD 中有鏈接,那么您可以執行以下操作:
Cell.findElement("a").click();
您必須構建一個動態選擇器來實現這一點。
例如:
private String rowRootSelector = "tr";
private String specificCellRoot = rowRootSelector + ":nth-of-type(%d) > td:nth-of-type(%d)";
而在以 Row 和 Column 作為輸入參數的方法中,必須構建選擇器。
String selector = String.format(specificCellRoot, rowIndex, columnIndex);
而且,現在您可以在該 Web 元素上單擊或執行任何其他操作。
driver.findElement(By.cssSelector(selector));
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.