如何在 Selenium 中处理动态网页表格

Selenium 中的网页表格

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

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

如何在 Selenium 中处理动态表格

以下是 Selenium 中销售动态网页表格的示例。根据输入的日期过滤器,行数会发生变化。因此,它是动态的。

Handle Dynamic Table in Selenium

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

使用 X-Path 定位网页表格元素

在定位网页元素之前,我们首先了解一下:

什么是网页元素?

网页元素就是 HTML 元素,如文本框、下拉列表、单选按钮、提交按钮等。这些 HTML 元素以开始标签开头,以结束标签结尾。

例如,

<p> 我的第一个 HTML 文档</p>。

获取要定位的网页元素的 X-path 的步骤。

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

Using X-Path to Locate Web Table Elements

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

Using X-Path to Locate Web Table Elements

步骤 3) 右键单击突出显示的网页元素 > 选择“复制”->“复制 X-path”选项。

Using X-Path to Locate Web Table Elements

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

示例:从动态网页表格中获取行数和列数

在 Selenium 中处理动态网页表格时,我们无法预测其行数和列数。

使用 Selenium WebDriver,我们可以找到

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

以下是获取 Selenium 中网页表格总行数和列数的程序

Fetch Number of Rows and Columns

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

代码解释

  • 这里我们首先声明了 WebDriver 对象“wd”,并将其初始化为 Chrome 驱动程序。
  • 我们使用 List <WebElement> 来获取“col”中的总列数。
  • findElements 命令返回与指定定位器匹配的所有元素的列表
  • 使用 findElements 和 X-path //*[@id=\”leftcontainer\”]/table/thead/tr/th,我们获取所有列
  • 同样,我们对行重复此过程。

输出

Fetch Number of Rows and Columns

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

假设我们需要表格的第 3 行和其第二个单元格的数据。请参见下表 –

Fetch Cell Value Of a Particular Row and Column

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

Fetch Cell Value Of a Particular Row and Column

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 行并使用 getText() 函数获取其文本
  • 使用 Xpath “//*[@id=\”leftcontainer\”]/table/tbody/tr[3]/td[2]” 查找第 3 行中的第 2 个单元格并使用 getText() 函数获取其文本

输出:

Fetch Cell Value Of a Particular Row and Column of The Dynamic Table

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

在此示例中,我们将获取特定列中所有值的最大值。

参考下表 –

Get Maximum of all the Values in a Column of Dynamic Table

这是代码

Get Maximum of all the Values in a Column of Dynamic Table

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 循环结束时打印出来

输出

Get Maximum of all the Values in a Column of Dynamic Table

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

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

Get all the values of a Dynamic Table

每行的列数不同。

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

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

这是代码

Get all the Values of a Dynamic Table

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")); 获取总列数
  • 我们遍历每一行的每一列并获取值。

输出:

Get all the Values of a Dynamic Table

摘要

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