如果 'text ' 在 Selenium Java 中匹配,如何在动态 table 中获取特定行值

How to get particular row values in dynamic table if the 'text ' matches in Selenium Java

我可以打印 webtable 中的所有值,但不确定如何获取特定行值。

这里我需要打印文本匹配的相应行值 'Aiden' 因为 Aiden 文本可能显示在任何行号中,没有固定位置。

 driver.get("https://demoqa.com/elements");

driver.manage().window().maximize();

driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
              
//clicking the left menu

              driver.findElement(By.xpath("//span[text()='Web Tables']")).click(); 
                      
              //driver.findElement(By.xpath("//div[@class='rt-table']")).click();
              Thread.sleep(5000);

// selecting the table      
      
              WebElement table = driver.findElement(By.xpath("//div[@class='rt-table']"));  

//selecting the table header    
      
                List<WebElement> tableheaders = table.findElements(By.xpath("//div[@class='rt-thead -header']"));  

//printing all the table header values
                
                for (WebElement headername : tableheaders) {   
                    String text = headername.getText();
                    System.out.println(text);
                }

//selecting all row values
                        
                List<WebElement> allrows = table.findElements(By.xpath("//div[@role='row' and @class='rt-tr -odd' or @class='rt-tr -even']")); 

// total row count

                int size = allrows.size();
                System.out.println("Rows size: "+size); 

// selecting all column values      
        
                for (int colnum = 0; colnum < size; colnum++) {
                    List<WebElement> colums = table.findElements(By.xpath("//div[@class='rt-td' and @role='gridcell'] /..")); 
                    WebElement firstColumn = colums.get(colnum);
                    System.out.println(firstColumn.getText());
                }

您可以创建一个空字符串变量,并在该行包含给定关键字时为其赋值

        String rowValue = "";
        for (WebElement webElement : tableRows) {
            if (webElement.getText().contains(searchedValue)) {
                rowValue = webElement.getText();
            }
        }
        System.out.println(rowValue);