Finding the rows and columns based on their dynamic changes and determining the table structure are necessary when working with dynamic tables in Selenium. To explain the scenario I use a Demo site.
@Test
public void dynamicTableHandling(){
WebDriver driver = new ChromeDriver();
driver.manage().window().maximize();
driver.get("https://practice.expandtesting.com/dynamic-table");
List<WebElement> Raws = driver.findElements(By.xpath("//table[@class='table table-striped']/tbody/tr"));
System.out.println("The no. of raws : "+Raws.size());
for(int r=1;r<=Raws.size();r++){
WebElement name = driver.findElement(By.xpath("//table[@class='table table-striped']/tbody/tr["+r+"]/td[1]"));
if(name.getText().equals("Chrome"))
{
String CPULoad = driver.findElement(By.xpath("//td[text()='Chrome']//following-sibling::*[contains(text(),\"%\")]")).getText();
System.out.println(CPULoad);
String Value = driver.findElement(By.id("chrome-cpu")).getText();
System.out.println(Value);
if(Value.contains(CPULoad)){
System.out.println("The CPU Load is equal");
}
else{
System.out.println("The CPU Load is not equal");
}
break;
}
}
driver.quit();
}
Here's how to use Java's Selenium WebDriver to manage a dynamic table with shifting rows and columns:
Code Explanation:
As the first step I did setup the driver and navigate to the Demo site.In that case I have Initialized a WebDriver instance (ChromeDriver) and Maximized the browser window and navigates to the given URL.
After that locates all rows in the table using the XPath.
//table[@class='table table-striped']/tbody/tr.
Then prints the total number of rows.
Next Iterated Through Rows using for Loop , through each row using an index (r)and extracted the name in the first column using XPath.
And I checked whether If the name in the first column matches "Chrome", then finds the CPU Load percentage dynamically using
//td[text()='Chrome']//following-sibling::*[contains(text(),\"%\")].
After that retrieved the CPU Load value from a specific element with ID chrome-cpu and compared the two values and prints a message about their equality. Finally Quits the browser after the test.
Top comments (0)