top of page
hand-businesswoman-touching-hand-artificial-intelligence-meaning-technology-connection-go-

Mastering Web Table Interactions in Selenium: Pagination and Sorting Strategies

Dynamic web tables are a common feature in modern web applications, displaying data in a structured format. However, when the amount of data is large, these tables often come with pagination controls. Testing such tables can be challenging. In this blog, we’ll explore how to handle pagination in Selenium WebDriver for dynamic web tables.


Understanding Pagination

Pagination is a technique used to divide large sets of data across multiple pages. Typically, a web table with pagination will have controls like “Next”, “Previous”, “First”, “Last”, and specific page numbers to navigate through the data.


The Challenge with Dynamic Web Tables

Dynamic web tables load data on demand, which means the content might change with each action. This poses a challenge for automation testing because the state of the web table can vary, making it difficult to predict and interact with.


Setting Up Selenium WebDriver

Before diving into pagination, ensure you have Selenium WebDriver set up in your project. You’ll also need a driver for the browser you intend to test on.


Handling Pagination in Selenium

Here’s a step-by-step approach to handling pagination in Selenium:


Step 1: Identify the Pagination Controls

Locate the web elements that represent the pagination controls. You’ll typically use locators like id, class, xpath, or cssSelector to find these elements.

Java

WebElement nextButton = driver.findElement(By.id("next-page"));

WebElement prevButton = driver.findElement(By.id("prev-page"));

// ... other controls


Step 2: Navigate Through Pages

Create a loop that allows you to navigate through the pages. You’ll need to decide when to stop, which could be when the “Next” button is disabled or when you’ve reached the last page number.

Java

while(isElementPresent(nextButton)) {

    // Perform your tests on the current page

    // Wait for the next page to load

    WebDriverWait wait = new WebDriverWait(driver, 10);

    wait.until(ExpectedConditions.visibilityOfElementLocated(By.id("table-id")));

}


Step 3: Interact with the Table

On each page, interact with the table as needed. This might involve reading data, clicking links, or performing other actions.

Java

List<WebElement> rows = driver.findElements(By.xpath("//table[@id='table-id']/tbody/tr"));

for(WebElement row : rows) {

    // Perform actions on each row

}


Step 4: Handle Dynamic Content

Since the table is dynamic, ensure that your script accounts for content that might load asynchronously.

Java

// Example of handling dynamic content

WebElement dynamicElement = wait.until(ExpectedConditions.presenceOfElementLocated(By.id("dynamic-element")));


Step 5: Clean Up

After testing, make sure to clean up any resources, close connections, and quit the WebDriver.

Java

driver.quit();

 

Extracting data from paginated tables and validating it against expected results involves several steps. Here’s a guide to help you through the process:


Extracting Data from Paginated Tables

  1. Identify the Table and Pagination Controls: Locate the web elements for the table and pagination controls using locators like id, class, xpath, or cssSelector.

  2. Navigate Through Pages: Use a loop to navigate through the pages. You may need to click on “Next” or specific page numbers and wait for the new page to load.

  3. Extract Table Data: On each page, extract the data from the table rows and cells. Store this data in a list or array for validation.

  4. Handle Dynamic Content: If the table content is loaded dynamically, use explicit waits to ensure the data is present before extraction.

Java

List<List<String>> allPagesData = new ArrayList<>();

do {

    List<WebElement> rows = driver.findElements(By.xpath("//table/tbody/tr"));

    for (WebElement row : rows) {

        List<WebElement> cells = row.findElements(By.xpath("td"));

        List<String> rowData = new ArrayList<>();

        for (WebElement cell : cells) {

            rowData.add(cell.getText());

        }

        allPagesData.add(rowData);

    }

} while (goToNextPage()); // Implement goToNextPage() to navigate and return false when no more pages are left


Validating Extracted Data

  1. Define Expected Results: Determine the expected results for the data you’re extracting. This could be a predefined list, array, or data from another source.

  2. Compare Extracted Data: Iterate over the extracted data and compare it with the expected results. You can use assertions for this purpose.

  3. Log Results: Log the results of the validation, noting any discrepancies between the extracted data and the expected results.

  4. Handle Errors: Implement error handling to manage any exceptions that occur during the validation process.

Here’s an example of how you might validate the data:

Java

List<List<String>> expectedData = ...; // Define your expected data

for (int i = 0; i < allPagesData.size(); i++) {

    Assert.assertEquals(allPagesData.get(i), expectedData.get(i), "Data mismatch on row: " + i);

}

 

Testing pagination controls in dynamic tables with Selenium involves several steps to ensure that the pagination functionality works as expected. Here’s a general approach:


Identify Pagination Controls: Locate the web elements for pagination controls such as “Next”, “Previous”, “First”, “Last”, and specific page numbers.

Navigate Through Pages: Use a loop to click through the pagination controls and navigate through the table pages.

Verify Table Data on Each Page: On each page, verify that the table data is loaded correctly and matches the expected results for that page.

Check Pagination State: Ensure that the state of pagination controls (enabled/disabled) is correct based on the current page.

Handle Dynamic Content: If the table data is loaded dynamically, use explicit waits to ensure the data is present before performing any checks.

Here’s an example code snippet in Java that demonstrates testing pagination:


Java

// Assume driver is already initialized

List<WebElement> paginationLinks = driver.findElements(By.xpath("//div[@class='pagination']/a"));

 

for (WebElement link : paginationLinks) {

    if (link.isDisplayed() && link.isEnabled()) {

        link.click();

        // Wait for the page to load

        WebDriverWait wait = new WebDriverWait(driver, 10);

        wait.until(ExpectedConditions.visibilityOfElementLocated(By.id("table-id")));

       

        // Perform checks on the table data

        // ...

    }

}

 

Handling sorting in dynamic tables using Selenium involves interacting with the table’s sorting controls and verifying that the data is sorted correctly. Here’s a general approach to handle sorting:


Identify the Sorting Controls: Locate the web elements for the column headers that trigger the sorting functionality. These are usually <th> elements within a <table>.

Trigger Sorting: Click on the column header to sort the table. You may need to click it multiple times to toggle between ascending and descending order.

Retrieve Table Data: After sorting, extract the data from the table to verify the sorting order. This typically involves fetching the text from each cell in the sorted column.

Validate Sorting: Compare the extracted data against the expected order. This can be done by copying the data into a list and using a sorting algorithm or collection sort method to check if the list is sorted.

Here’s an example code snippet in Java that demonstrates these steps:


Java

// Click the column header to sort the table

WebElement columnHeader = driver.findElement(By.xpath("//th[@id='header-id']"));

 

// Wait for the sorting to complete (use explicit wait if necessary)

Thread.sleep(1000); // Replace with a proper wait

// Retrieve the data from the sorted column

List<WebElement> sortedDataElements = driver.findElements(By.xpath("//td[@class='sorted-column']"));

List<String> sortedData = new ArrayList<>();

for (WebElement element : sortedDataElements) {

    sortedData.add(element.getText());

}

 

// Validate the sorting order

List<String> originalData = new ArrayList<>(sortedData);

Collections.sort(originalData);

Assert.assertEquals(sortedData, originalData, "The column is not sorted correctly.");

 

Remember to replace the XPath expressions with the actual locators for your specific table. Also, ensure that you handle any dynamic behavior such as asynchronous data loading or pagination, which may require additional logic to navigate and extract data correctly.


Advanced Sorting Techniques in Selenium for Dynamic Web Tables

Handling Multiple Sort Criteria


Dynamic tables often allow sorting by multiple columns. Selenium can automate the process of sorting by one column and then another, ensuring that secondary sort criteria are applied correctly.


Java

// Click the primary column header

WebElement primaryColumnHeader = driver.findElement(By.xpath("//th[@id='primary-header-id']"));

// Click the secondary column header

WebElement secondaryColumnHeader = driver.findElement(By.xpath("//th[@id='secondary-header-id']"));

// Validate the sorting order for both criteria


Sorting Verification


Verifying the sorting functionality requires careful extraction and comparison of table data. For numerical and date columns, ensure that the values are parsed into their respective types before comparison.

Java

List<Integer> numericColumnData = sortedElements.stream()

    .map(e -> Integer.parseInt(e.getText().replace(",", ""))) // Remove formatting

    .collect(Collectors.toList());

// Verify the list is sorted numerically

Assert.assertTrue(Ordering.natural().isOrdered(numericColumnData), "Numeric column is not sorted correctly.");

 

Sorting with Special Characters


When dealing with strings that contain special characters or mixed case, you may need to implement custom sorting logic to accurately reflect the application’s sorting behavior.

Java

// Custom comparator for special character sorting

Comparator<String> customComparator = new Comparator<String>() {

    @Override

    public int compare(String o1, String o2) {

        // Implement comparison logic that matches the application's sorting

        return o1.compareToIgnoreCase(o2);

    }

};

Collections.sort(expectedSortedData, customComparator);

Assert.assertEquals(sortedData, expectedSortedData, "The column with special characters is not sorted correctly.");


Handling Infinite Scrolling


Some dynamic tables load more data as you scroll down, which can be considered a form of pagination. Selenium can automate scrolling and ensure that sorting remains consistent as new data loads.

Java

JavascriptExecutor js = (JavascriptExecutor) driver;

js.executeScript("window.scrollTo(0, document.body.scrollHeight)");

// Wait for new data to load and then perform sorting validation

 

Performance Testing


Sorting large datasets can be slow. Use Selenium to measure the time taken to sort and ensure it’s within acceptable limits.

Java

long startTime = System.currentTimeMillis();

columnHeader.click(); // Trigger sorting

// Wait for sorting to complete

long endTime = System.currentTimeMillis();

Assert.assertTrue((endTime - startTime) < 5000, "Sorting took too long.");


Conclusion


Handling pagination in Selenium requires careful planning and execution. By following the steps outlined in this guide, you can effectively navigate and test dynamic web tables with pagination controls. Remember to adapt the code to fit the specific structure and behavior of the web table you’re testing.

 

Testing sorting in dynamic web tables with Selenium requires a thorough understanding of the table’s behavior and the data it contains. By implementing advanced sorting techniques and validations, you can ensure that your automated tests accurately reflect the user experience and catch potential issues before they affect end-users.

This extended content provides a comprehensive look at handling complex sorting scenarios in dynamic web tables using Selenium WebDriver. With these techniques, you can build robust automated tests that ensure the sorting functionality works flawlessly across various data types and user interactions. Keep refining your automation strategies for the best outcomes!

46 views0 comments

Comentarios

Obtuvo 0 de 5 estrellas.
Aún no hay calificaciones

Agrega una calificación
bottom of page