如何处理动态 Web 表 Selenium

网页表格 Selenium

网络上发布的 HTML 表格有两种类型:

  1. 静态表:数据是静态的,即行数和列数是固定的。
  2. 动态表:数据是动态的,即行数和列数不是固定的。

如何处理动态表 Selenium

下面是一个动态网页表格的例子 Selenium 针对销售。根据输入日期过滤器,行数将发生改变。因此,它本质上是动态的。

处理动态表 Selenium

处理静态表很容易,但处理动态表 Selenium 有点困难,因为行和列不是恒定的。

使用 X-Path 定位 Web 表元素

在定位 Web 元素之前,我们首先要了解-

什么是网络元素?

Web 元素不过是 HTML 元素,例如文本框、下拉单选按钮、提交按钮等。这些 HTML 元素是用 开始 标签并以 end 标签。

例如,

我的第一个 HTML 文档

获取我们想要定位的 Web 元素的 X-path 的步骤。

步骤1) 在 Chrome 中,转到 https://demo.guru99.com/test/web-table-element.php

使用 X-Path 定位 Web 表元素

步骤2) 右键单击要获取其 x-path 的 Web 元素。在我们的例子中,右键单击“公司”选择检查选项。将显示以下屏幕 -

使用 X-Path 定位 Web 表元素

步骤3) 右键单击突出显示的 Web 元素 > 选择复制 -> 复制 x-path 选项。

使用 X-Path 定位 Web 表元素

步骤4) 使用复制的 X-path “//*[@id=”leftcontainer”]/table/thead/tr/th [1]” Selenium WebDriver 来定位元素。

示例:从动态 WebTable 中获取行数和列数

虽然动态网页表格处理 Selenium,我们无法预测它的行数和列数。

运用 Selenium 网络驱动程序,我们可以找到

  • 网页表格的行数和列数 Selenium
  • X 行或 Y 列的数据。

下面是用于获取处理网络表的总行数和列数的程序 Selenium:

获取行数和列数

import java.text.ParseException;
import java.util.List;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
public class Noofrowsandcols {
    
public static void main(String[] args) throws ParseException {
    	WebDriver wd;
	  System.setProperty("webdriver.chrome.driver","G://chromedriver.exe");
	  wd= new ChromeDriver();
        wd.get("https://demo.guru99.com/test/web-table-element.php");         
        //No.of Columns
        List <webelement> col = wd.findElements(By.xpath(".//*[@id=\"leftcontainer\"]/table/thead/tr/th"));
        System.out.println("No of cols are : " +col.size()); 
        //No.of rows 
        List <webelement> rows = wd.findElements(By.xpath(".//*[@id='leftcontainer']/table/tbody/tr/td[1]")); 
        System.out.println("No of rows are : " + rows.size());
        wd.close();
    }
}

代码说明:

  • 这里我们首先声明 Web Driver 对象“wd”并将其初始化为 chrome 驱动程序。
  • 我们使用列表到“col”中的总列数。
  • findElements 命令返回与指定定位器匹配的所有元素的列表
  • 使用 findElements 和 X-path //*[@id=\”leftcontainer\”]/table/thead/tr/th 我们得到所有列
  • 类似地,我们对行重复该过程。

输出:

获取行数和列数

示例:获取动态表特定行和列的单元格值

假设我们需要 3rd 表格的行及其第二个单元格的数据。请参阅下表:

获取特定行和列的单元格值

在上表中,数据会在一段时间后定期更新。您尝试检索的数据将与上面的屏幕截图不同。但是,代码保持不变。以下是获取 3rd 行和 2nd 列的数据。

获取特定行和列的单元格值

import java.text.ParseException;
import java.util.List;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import java.util.concurrent.TimeUnit;


public class RowandCell {
    public static void main(String[] args) throws ParseException {
    	WebDriver wd;
		System.setProperty("webdriver.chrome.driver","G://chromedriver.exe");
		 wd= new ChromeDriver();
		 wd.get("https://demo.guru99.com/test/web-table-element.php"); 
		 wd.manage().timeouts().implicitlyWait(20, TimeUnit.SECONDS);
		 WebElement baseTable = wd.findElement(By.tagName("table"));
		  
		 //To find third row of table
		 WebElement tableRow = baseTable.findElement(By.xpath("//*[@id=\"leftcontainer\"]/table/tbody/tr[3]"));
         String rowtext = tableRow.getText();
		 System.out.println("Third row of table : "+rowtext);
		    
		    //to get 3rd row's 2nd column data
		    WebElement cellIneed = tableRow.findElement(By.xpath("//*[@id=\"leftcontainer\"]/table/tbody/tr[3]/td[2]"));
		    String valueIneed = cellIneed.getText();
		    System.out.println("Cell value is : " + valueIneed); 
		    wd.close();
    }
}

代码说明:

  • 使用定位器属性“tagname”来定位表。
  • 运用 XPath的 “//*[@id=\”leftcontainer\”]/table/tbody/tr[3]” 找到第 3 个rd 行并使用 getText () 函数获取其文本
  • 使用 Xpath “//*[@id=\”leftcontainer\”]/table/tbody/tr[3]/td[2]” 找到 2 中的第 3 个单元格rd 行并使用 getText () 函数获取其文本

输出:

获取动态表特定行和列的单元格值

示例:获取动态表某一列中所有值的最大值

在这个例子中,我们将获得特定列中所有值的最大值。

请参阅下表 –

获取动态表某一列中所有值的最大值

这是代码

获取动态表某一列中所有值的最大值

import java.text.ParseException;
import java.util.List;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import java.text.NumberFormat;


public class MaxFromTable {
    public static void main(String[] args) throws ParseException {
    	WebDriver wd;
		System.setProperty("webdriver.chrome.driver","G://chromedriver.exe");
		 wd= new ChromeDriver();
		 wd.get("https://demo.guru99.com/test/web-table-element.php"); 
		 String max;
	     double m=0,r=0;
		 
	       //No. of Columns
	        List <webelement> col = wd.findElements(By.xpath(".//*[@id='leftcontainer']/table/thead/tr/th"));
	        System.out.println("Total No of columns are : " +col.size());
	        //No.of rows
	        List <webelement> rows = wd.findElements(By.xpath (".//*[@id='leftcontainer']/table/tbody/tr/td[1]"));
	        System.out.println("Total No of rows are : " + rows.size());
	        for (int i =1;i<rows.size();i++)
	        {    
	            max= wd.findElement(By.xpath("html/body/div[1]/div[5]/table/tbody/tr[" + (i+1)+ "]/td[4]")).getText();
	            NumberFormat f =NumberFormat.getNumberInstance(); 
	            Number num = f.parse(max);
	            max = num.toString();
	            m = Double.parseDouble(max);
	            if(m>r)
	             {    
	                r=m;
	             }
	        }
	        System.out.println("Maximum current price is : "+ r);
    }
}

</webelement></webelement>

代码说明:

  • 使用 chrome 驱动程序,我们定位网络表并使用 XPath “.//*[@id='leftcontainer']/table/tbody/tr/td[1]” 获取总行数
  • 使用 for 循环,我们遍历总行数并逐一获取值。要获取下一行,我们在 XPath 中使用 (i+1)
  • 我们将旧值与新值进行比较,并在 for 循环结束时打印最大值

输出

获取动态表某一列中所有值的最大值

示例:获取动态表的所有值

请考虑下表: https://demo.guru99.com/test/table.html

获取动态表的所有值

每行的列数不同。

这里,第 1、2 和 4 行有 3 个单元格,第 3 行有 2 个单元格,第 5 行有 1 个单元格。

我们需要获取所有单元格的值

这是代码:

获取动态表的所有值

import java.text.ParseException;
import java.util.List;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import java.util.concurrent.TimeUnit;
import org.openqa.selenium.chrome.ChromeDriver;



public class NofRowsColmns {
    public static void main(String[] args) throws ParseException {
    	WebDriver wd;
    	System.setProperty("webdriver.chrome.driver","G://chromedriver.exe");
    	wd = new ChromeDriver();
    	wd.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS);
    	wd.get("https://demo.guru99.com/test/table.html");
    	//To locate table.
    	WebElement mytable = wd.findElement(By.xpath("/html/body/table/tbody"));
    	//To locate rows of table. 
    	List < WebElement > rows_table = mytable.findElements(By.tagName("tr"));
    	//To calculate no of rows In table.
    	int rows_count = rows_table.size();
    	//Loop will execute till the last row of table.
    	for (int row = 0; row < rows_count; row++) {
    	    //To locate columns(cells) of that specific row.
    	    List < WebElement > Columns_row = rows_table.get(row).findElements(By.tagName("td"));
    	    //To calculate no of columns (cells). In that specific row.
    	    int columns_count = Columns_row.size();
    	    System.out.println("Number of cells In Row " + row + " are " + columns_count);
    	    //Loop will execute till the last cell of that specific row.
    	    for (int column = 0; column < columns_count; column++) {
    	        // To retrieve text from that specific cell.
    	        String celtext = Columns_row.get(column).getText();
    	        System.out.println("Cell Value of row number " + row + " and column number " + column + " Is " + celtext);
    	    }
    	    System.out.println("-------------------------------------------------- ");
    	}
   	}
}

代码说明:

  • rows_count 给出总行数
  • 对于每一行,我们使用以下方法获取总列数 rows_table.get(row).findElements(By.tagName("td"));
  • 我们遍历每一行和每一列并获取值。

输出:

获取动态表的所有值

结语

  • By.xpath() 通常用于访问表格元素。
  • 静态网页表格 Selenium 本质上是一致的。即它们确实具有固定的行数以及单元格数据。
  • 动态网络表不一致,即它们没有固定数量的行和单元格数据。
  • 使用 selenium web 驱动程序,我们可以轻松处理动态网络表。
  • Selenium Webdriver 允许我们通过其访问动态网页表 X-路径。了解如何在 Selenium 中处理 Web 表对于有效的自动化测试至关重要。