java - 从表值动态生成 CSS 选择器

标签 java selenium selenium-webdriver

我们有一个建立在大量表格之上的网站。行中的每个单元格都是可单击的。我正在研究一种通过提供我想要单击的表名称和值来动态构建 cssSelector 信息的方法。我已经很接近了(我想)。

使用ToolsQA处的练习表,假设我想为值“Taiwan”构建 cssSelector。

其 cssSelector 为:.tsc_table_s13 > tbody:nth-child(4) > tr:nth-child(3) > td:nth-child(2)

我正在迭代表格,并已成功能够使用我指定的值(“台湾”)输入单元格,但是,我不确定如何获取当前所在行和列的值.

这是我迄今为止使用的代码:

driver.get("http://toolsqa.com/automation-practice-table/");

String table = ".tsc_table_s13 > tbody:nth-child(4)";
String cellValue = "Taiwan";

getCell(table, cellValue);

    // Get the cell of a particular value
    public static void getCell(String table, String value) throws IOException{

        // Grab the table 
        WebElement tableName = driver.findElement(By.cssSelector(table)); 

        // Now get all the TR elements from the table 
        List<WebElement> allRows = tableName.findElements(By.tagName("tr")); 

        // And iterate over them, getting the cells 
        for (WebElement row : allRows) { 
            List<WebElement> cells = row.findElements(By.tagName("td")); 

            // Print the contents of each cell
            for (WebElement cell : cells) {
//              System.out.println(cell.getText());
                if (cell.getText().equals(value))
                {
                    String cellValue = table + " > tr:nth-child(" + row. + ") > td:nth-child(" + cell + ")";
                    System.out.println(cellValue);

                } // end if text equals

            } // end for loop for cells
        } // end for loop for all rows

    } // end getCell function

最佳答案

这里有一个简单的示例,说明如何使用 XPath 在表中查找文本并获取对元素的引用。您提供要搜索的文本,它会插入到 XPath 中。下面的 XPath 搜索包含该文本的 TD。这只是一个简单的案例。如果您的表格中有很多重复的文本,您必须发布一些示例,以便我可以更新代码以将其考虑在内。

String searchText = "China";
driver.get("http://toolsqa.com/automation-practice-table/");
WebElement e = driver.findElement(By.xpath("//td[text()='" + searchText + "']"));
System.out.println(e.getText()); // you can get the text in the cell
System.out.println(e.getAttribute("outerHTML")); // you can get the HTML of the TD
e.click(); // you can click the element also but in this case it won't do anything since it's just a TD with text

关于java - 从表值动态生成 CSS 选择器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38127203/

相关文章:

c# - 在 Visual Studio 的引用部分下的 Nuget 包管理器的结果窗口中未获取 Selenium Webdriver

python - 我们如何在循环中创建 selenium webdriver 对象并在循环结束后关闭窗口?

java - 远程 jprofiler 集成

java - spring mvc 应用程序的正确配置

java - 为什么不弹出警报?

python - 使用selenium从元素获取src

selenium - 操作系统错误: [Errno 8] Exec format error: '/home/ec2-user/Desktop/chromedriver' error using Chromedriver in AWS EC2 ARM flavour machine

python - Selenium/Python - 如何按随机选择的像素滚动?

java - Jersey : File Uploading Issue

Java、泛型和 Classe<Generic> 问题