【问题标题】:Selenium Webdriver Java: How to click on a particular cell in table using row and column numbersSelenium Webdriver Java:如何使用行号和列号单击表格中的特定单元格
【发布时间】:2016-06-02 17:05:46
【问题描述】:

我已经编写了一个代码来验证该行中是否存在给定的文本,但是我如何单击特定的单元格?请帮帮我。
下面是我为验证文本而编写的代码。

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();
  }
}  

【问题讨论】:

  • 我想点击表格中的特定单元格,因为表格中的单元格可能有需要输入的下拉菜单或文本字段。

标签: java selenium webdriver


【解决方案1】:

你可以修改你的循环来点击,而不是连接一个巨大的字符串

for(WebElement row: allrows){
    List<WebElement> Cells = row.findElements(By.tagName("td"));
    for(WebElement Cell:Cells){
        if (Cell.getText().contains("Jackson"))
            Cell.click();
    }
}

但请记住,单击 &lt;td&gt; 可能实际上不会触发,因为 &lt;td&gt; 可能没有监听单击事件。如果它在 TD 中有链接,那么您可以执行以下操作:

Cell.findElement("a").click();

【讨论】:

  • 感谢您的建议@sircapsalot。但我想使用行号和列号单击表格中的任何单元格。如果你能帮助我,那就太好了。谢谢
【解决方案2】:

您必须构建一个动态选择器来实现这一点。

例如:

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));

【讨论】:

    猜你喜欢
    • 2020-03-18
    • 2012-05-16
    • 2013-07-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-03-14
    相关资源
    最近更新 更多