Selenium Pagination Tutorial: How to Handle Page Navigation
Faisal Khatri
Posted On: September 13, 2024
133013 Views
16 Min Read
As websites are becoming an integral part of the business, they must have a good UI that provides the best user experience and loads the content quickly. Websites can be categorized into two types based on the categorization of their content: paginated and infinite-scrolling websites. The paginated website divides the content of the website into different pages, allowing the user to access all the available content on the different pages of the website one by one seamlessly.
In this Selenium pagination tutorial, we will learn about paginated websites, their importance, and how to automate pagination using Selenium Java on the LambdaTest cloud grid.
TABLE OF CONTENTS
What Is Pagination?
Pagination is the method of segregating the content of the website across multiple pages. The users can access the different pages on the website by using the navigation panel provided at the bottom of the page. The navigation panel has buttons with page numbers and also dedicated buttons to navigate to the first, next, previous, and last pages, respectively.
The following screenshot from the LambaTest eCommerce Playground shows pagination for the different products available on the website.
As we can see the content is paginated on the website to make it easier for the end users to seamlessly navigate through the different products available and accordingly search and select the required one.
Shopping websites such as Amazon and eBay use pagination to display the list of multiple products online on different pages. Pagination helps the users smoothly transition to the different pages and search for the required product easily.
Single-page applications such as Gmail, Facebook, etc. dynamically rewrite the current web page with the latest data from the web server instead of the web browser loading the entire new web page. Gmail uses pagination to load the email, whereas Facebook uses infinite scrolling to load its new feed.
Automate pagination testing on the cloud. Try LambdaTest Today!
Why Is Pagination Important?
The basic idea behind adding pagination to a website is that the users can be presented with the content of the website page by page. This helps the users easily check the specific content they are looking for. However, in technical terms, it has more to do with rather than just presentation.
Consider a scenario in which a website displays content using pagination, and the end user has a slow network connection. In such a case, it can be ensured that the website will at least load the pagination data that the user has asked for. However, in a similar situation with infinite scrolling websites, chances are no content would be loaded due to low internet speed, and the data loading icon might be displayed continuously.
The following points will help in better understanding the requirement for pagination in a website.
- Speed up the page-loading process
- Improved user experience
Performance plays a vital part for the websites. As per the statistics collected by WebFX, around 40% of web users will abandon the website if it takes more than 3 seconds to load.
This issue can be addressed by delivering content in smaller chunks and loading pages incrementally. This approach speeds up the page load time and enhances the user’s navigation experience.
Pagination helps in faster and more responsive web pages, thus providing a better user experience to the end users. With the help of pagination, users can quickly navigate to the different pages to check out the desired content on the website.
As we learned that pagination solves multiple problems of a website, it is important to perform thorough testing of pagination on the website to give the end users a bug free experience.
So, let’s now delve into the other part of this Selenium pagination tutorial, where we discuss how to automate pagination using Selenium Java on cloud testing platforms like LambdaTest.
Selenium Pagination Demo: How to Automate Page Navigation?
In this section of the Selenium pagination tutorial, we will learn how to automate pagination using Selenium Java on the LambdaTest cloud.
LambdaTest is an AI-powered test execution platform that helps you automate pagination tests with Selenium online. You can run these tests on over 3000+ real desktop browsers and operating system combinations.
The following test scenarios will be taken into account in order to demo the Selenium pagination tests.
Test Scenario 1:
|
Test Scenario 2:
|
Test Scenario 3:
|
Test Scenario 4:
|
Setting up the Project
To start with, Maven is used as a build tool, and TestNG is used as the test runner. Selenium Java will be used for writing the web automation tests.
So, let’s first create a new Maven project and update the dependencies for Selenium WebDriver and TestNG in the pom.xml file.
The project configuration is complete with updating the dependencies for Selenium WebDriver and TestNG in the pom.xml file. Next, we need to configure the Selenium WebDriver to run the tests on the LambdaTest cloud platform.
In the next section of this blog on Selenium pagination, we will learn how to configure the tests.
Configuring the Tests
The RemoteWebDriver class will be used to implement the Selenium WebDriver. Additionally, we need to pass on the required capabilities for configuring the browser, browser version, platform, and its version for running the tests.
These capabilities can be easily set up using the LambdaTest Capabilities Generator website. This website allows us to set the capabilities using the UI and generates the code on run time that can be directly used in the automation tests.
LambdaTest Username and Access Key are the two important values that need to be passed in the tests without which the tests can not be run on the LambdaTest cloud grid. These values will be supplied using the environment variable on run time.
Let’s create a new class named SeleniumPaginationTests.java that will have all the test scenarios covered.
1 2 3 4 5 6 |
public class SeleniumPaginationTests { private RemoteWebDriver driver; // ... } |
The setup() method created inside the SeleniumPaginationTests class has the configuration code for running the tests on the LambdaTest cloud grid. This configuration has the LambdaTest userName, accessKey, and the capabilities that were discussed in the earlier section.
1 2 3 4 5 6 7 8 9 10 11 12 |
@BeforeTest public void setup() { final String userName = System.getenv("LT_USERNAME") == null ? "LT_USERNAME" : System.getenv("LT_USERNAME"); final String accessKey = System.getenv("LT_ACCESS_KEY") == null ? "LT_ACCESS_KEY" : System.getenv("LT_ACCESS_KEY"); final String gridUrl = "@hub.lambdatest.com/wd/hub"; try { this.driver = new RemoteWebDriver(new URL("http://" + userName + ":" + accessKey + gridUrl), getChromeOptions()); } catch (final MalformedURLException e) { System.out.println("Could not start the remote session on LambdaTest cloud grid"); } this.driver.manage().timeouts().implicitlyWait(Duration.ofSeconds(5)); } |
The RemoteWebDriver class is used to implement Selenium WebDriver in order to execute the tests on the LambdaTest cloud grid. The tests will be executed on the latest version of Chrome browser on the Windows 10 platform.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
public ChromeOptions getChromeOptions() { final var browserOptions = new ChromeOptions(); browserOptions.setPlatformName("Windows 10"); browserOptions.setBrowserVersion("latest"); final HashMap<String, Object> ltOptions = new HashMap<String, Object>(); ltOptions.put("project", "Pagination tests - LambdaTest e-commerce website"); ltOptions.put("build", "Automating pagination of LambdaTest e-commerce website"); ltOptions.put("name", "Pagination tests - LambdaTest e-commerce website"); ltOptions.put("w3c", true); ltOptions.put("plugin", "java-testNG"); browserOptions.setCapability("LT:Options", ltOptions); return browserOptions; } |
These capabilities, such as platform name, browser name, its respective versions, etc., required for the cloud platform are supplied using the getChromeOptions() method.
Notice the @BeforeTest annotation mentioned above in the setup() method. This annotation by TestNG is used so this method gets executed first before the test gets executed, setting all the configurations required for running the tests.
Similarly, the teardown() method is created that will update the status for the test on the LambdaTest cloud grid. The status variable will be updated in the individual tests based on the test assertions getting passed/fail.
Finally, it will gracefully quit the RemoteWebDriver session.
1 2 3 4 5 |
@AfterTest public void tearDown() { driver.executeScript("lambda-status=" + status); this.driver.quit(); } |
This method will be executed after the test is run using the @AfterTest annotation from TestNG.
Writing the Tests
In this section of this blog on Selenium pagination, we will write tests for all the test scenarios to demo the Selenium pagination tests.
Implementation: Test Scenario 1
In the first test scenario, we will be navigating to the product page of the LambdaTest eCommerce playground website.
Next, the page number displayed in the pagination details at the bottom of the page will be verified.
Finally, the names of all the products displayed on all pages till the last page will be printed on the console.
1 2 3 4 5 6 7 8 9 |
@Test public void testProductDetailsOnAllPage() { this.driver.get("https://ecommerce-playground.lambdatest.io/index.php?route=product/category&path=25_28"); final ProductPage productPage = new ProductPage(this.driver); assertTrue(productPage.paginationDetails().contains("5 Pages")); productPage.printProductDetailsOnPages(); status = “passed”; } |
The testProductDetailsOnAllPage() method created in the SeleniumPaginationTests class will perform all the action steps as discussed for the test scenario.
A separate class, ProductPage, has been created, which has all the implementation steps of the test scenario 1.
1 2 3 4 5 6 7 8 9 10 11 |
public class ProductPage { private final WebDriver driver; private String status = “failed”; public ProductPage(final WebDriver driver) { this.driver = driver; } //… } |
The paginationdetails() method returns the pagination details in String format.
1 2 3 |
public String paginationDetails() { return this.driver.findElement(By.cssSelector(".content-pagination .text-right")).getText(); } |
The printProductDetailsOnPages() method is created in the ProductPage class that will print the product name displayed on every page by using the Next navigation button and repeat the same action till the last page.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
public void printProductDetailsOnPages() { while (isNavigationPanelDisplayed()) { final List<WebElement> products = this.driver.findElements(By.cssSelector(".product-layout")); for (final WebElement product : products) { final WebElement productName = product.findElement(By.cssSelector(".caption h4 a")); System.out.println(productName.getText()); } if (isNextButtonIsDisplayed()) { this.driver.findElement(By.linkText(">")).click(); } else { break; } } } |
A while loop is used to check that the navigation panel is displayed at the bottom of the page. Next, it will find all the elements with the CSS Selector “.product-layout”; this is actually a block of the product with its details on the page.
Once the product block is found, the product name will be extracted using the CSS Selector “.caption h4 a” and its text will be fetched using the getText() method of Selenium WebDriver. All the product names available on the page will be printed on the console.
Next, the code will check if the Next button is displayed on the page. If the Next button is displayed, it will be located using the Link Text “>” and a click action will be performed on it.
As the next page button uses the icon “>” in the navigation panel hence it is used in the linkText locator strategy.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
private boolean isNextButtonIsDisplayed() { try { return this.driver.findElement(By.linkText(">")).isDisplayed(); } catch (NoSuchElementException | StaleElementReferenceException e) { return false; } } private boolean isNavigationPanelDisplayed() { try { return this.driver.findElement(By.cssSelector("ul.pagination")).isDisplayed(); } catch (NoSuchElementException | StaleElementReferenceException e) { return false; } } |
The isDisplayed() method of Selenium WebDriver returns a boolean value. It will return true if the WebElement is displayed, else it will return false. This method is used for checking if the Next button is displayed in the navigation panel or not.
On reaching the last page, where the Next button will not be displayed, NoSuchElementException will be thrown, which will be caught in the catch() block, and it will return false. Eventually, the break statement will be called, which will end the test.
Implementation: Test Scenario 2
In the second scenario, we will navigate to the product page of the LambdaTest eCommerce Playground website, change the filter record value to “50” and verify that the pagination details at the bottom of the page display the page number correctly.
1 2 3 4 5 6 7 8 9 |
@Test public void testFilterRecordsOnPage() { this.driver.get("https://ecommerce-playground.lambdatest.io/index.php?route=product/category&path=25_28"); final ProductPage productPage = new ProductPage(this.driver); productPage.changeFilterRecord("50"); assertTrue(productPage.paginationDetails().contains("2 Pages")); status=”passed”; } |
The testFilterRecordsOnPage() test method created in the SeleniumPaginationTests class will perform all the test steps for test scenario 2.
The changeFilterRecord() method created in the ProductPage class takes the record number as a parameter. It will locate the filter dropdown box and select the record number as provided as input by the user using the selectByVisibleText() method of the Select class from Selenium WebDriver.
1 2 3 4 5 |
public void changeFilterRecord(final String recordNumber) { final WebElement recordFilter = this.driver.findElement(By.cssSelector(".custom-select")); final Select select = new Select(recordFilter); select.selectByVisibleText(recordNumber); } |
After the filter is applied, the assertion will be performed by using the assertTrue() method from TestNG. The paginationDetails() method used in assertion returns the pagination details in the String format.
1 2 3 |
public String paginationDetails() { return this.driver.findElement(By.cssSelector(".content-pagination .text-right")).getText(); } |
The assertion checks if the pagination details contain the expected number of pages.
Implementation: Test Scenario 3
In the third scenario, we will be searching for a product name, “HP LP3065”, on the product page of the LambdaTest eCommerce Playground website.
The condition for the search is that if the product is found, the text “Product found” should be printed on the console. After searching all the available pages, if the product is not found, it should print the text “Product not found”.
1 2 3 4 5 6 7 8 |
@Test public void testSearchForProduct() { this.driver.get("https://ecommerce-playground.lambdatest.io/index.php?route=product/category&path=25_28"); final ProductPage productPage = new ProductPage(this.driver); productPage.searchForProduct("HP LP3065"); status=”passed”; } |
The testSearchForProduct() test method created in the SeleniumPaginationTests class will perform all the test steps for test scenario 3.
In the ProductPage class, the searchForProduct() method is created, which takes the product name as a parameter. This product name will be searched on the page.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 |
public void searchForProduct(final String nameOfProduct) { boolean found = false; while (!found) { final List<WebElement> products = this.driver.findElements(By.cssSelector(".product-layout")); for (final WebElement product : products) { final String productName = product.findElement(By.cssSelector(".caption h4 a")).getText(); if (nameOfProduct.equals(productName)) { System.out.println("Product found!"); found = true; break; } } if (isNextButtonIsDisplayed()) { this.driver.findElement(By.linkText(">")).click(); } else { System.out.println("Product Not Found!"); break; } } } |
In the searchForProduct() method, a while loop is used to keep checking if the product is found on the page or not. This loop starts with searching for the product on the page by locating all the product blocks and going through the product names one by one. If the product name is found, the text “Product found” is printed in the console, and the loop ends.
In case the product name is not found on the current page, the code checks if the Next navigation button is displayed on the page. If the Next navigation button is displayed, it will click on it, and the same search will be performed on the next page. This process goes on till the last page.
In case the product name is not found after going through each page till the last page, the text “Product Not found” is printed on the console, and the test ends.
Implementation: Test Scenario 4
In the fourth scenario, after launching the product page on the LambdaTest eCommerce Playground website. The “First” and “Last” navigation buttons on the navigation panel will be clicked, and assertions will be performed to check that the navigation was successful.
1 2 3 4 5 6 7 8 9 10 11 12 |
@Test public void testPageNavigation() { this.driver.get("https://ecommerce-playground.lambdatest.io/index.php?route=product/category&path=25_28"); final ProductPage productPage = new ProductPage(this.driver); productPage.navigateToLastPage(); assertTrue(productPage.paginationDetails().contains("Showing 61 to 75 of 75")); productPage.navigateToFirstPage(); assertTrue(productPage.paginationDetails().contains("Showing 1 to 15 of 75")); status=”passed”; } |
The testPageNavigation() test method is created within the SeleniumPaginationTests class that will perform the navigation to the first and the last page and accordingly assert that the correct pages are displayed.
The navigateToLastPage() method that is created in the ProductPage class locates the Last navigation button and performs a click on it.
1 2 3 |
public void navigateToLastPage() { this.driver.findElement(By.linkText(">|")).click(); } |
Likewise, the navigateToFirstPage() method locates the First navigation button and performs a click on it.
1 2 3 |
public void navigateToFirstPage() { this.driver.findElement(By.linkText("|<")).click(); } |
The paginationDetails() method returns the pagination details text displayed at the bottom of the page. This text is used to perform the assertions.
1 2 3 |
public String paginationDetails() { return this.driver.findElement(By.cssSelector(".content-pagination .text-right")).getText(); } |
When the last page is navigated, the assertion is performed to check that the pagination details display the text “Showing 61 to 75 of 75”. Similarly, when the First navigation button is clicked, it is checked that the text “Showing 1 to 15 of 75” is displayed in the pagination details.
Executing the Tests
The following testng.xml file is created which will help in executing all the tests one by one. These tests will be executed on the LambdaTest cloud grid.
Before executing the tests, make sure to add the LambdaTest Username and Access Key in the environment variables, as these are mandatory values that are needed to run the tests on the LambdaTest cloud grid.
To start running the tests, right-click on the testng-pagination-tests.xml file and select the option “Run ../testng-pagination-tests.xml” to execute the test.
The following screenshot from IntelliJ shows the successful execution of tests using IntelliJ IDE.
The test execution details can be found on the LambdaTest dashboard.
The LambdaTest build details window shows a detailed insight into the test execution. It provides details such as platform name, browser name, and its version, video of the test execution, and step-by-step test execution details.
The screenshot of the test execution, as well as the logs could also be found on the LambdaTest build details window.
Final Thoughts
Pagination plays a vital role in displaying the content of the website. It can be helpful in showing the category’s product list, displaying the records of financial data, or a summarized list of any information meant for the end users. It helps in delivering a better user experience to the customers.
Testing pagination and checking the data manually could prove to be a very tedious task. Hence, test automation should be used as it can help in running multiple tests easily and provide accurate test results.
In this Selenium pagination tutorial, we learned about the importance of pagination and how to automate pagination using Selenium Java with some real-world examples.
I hope this blog helped you learn new techniques of test automation.
Happy Testing!!
Frequently Asked Questions (FAQs)
What is pagination in automation?
Pagination in automation refers to the process of handling web pages or data that are divided into multiple sections or pages. This is commonly seen in websites displaying large amounts of content, like search results or product listings, where only a subset of the data is shown at a time, with navigation options (e.g., “Next,” “Previous,” or page numbers) to view more.
How to implement pagination in Java?
In Java, pagination refers to the process of dividing a large set of data into smaller, manageable chunks (pages), allowing users to navigate through them one page at a time. It’s commonly used when displaying large lists of items, like search results, products in an online store, or database records, where displaying all data at once would be inefficient.
- Determine Page Number and Size.
- Calculate Indexes.
- Extract Data for the Page.
- Handle Edge Cases.
Got Questions? Drop them on LambdaTest Community. Visit now