Scrolling in Selenium Webdriver

Scrolling in Selenium Webdriver

Scrolling a webpage is required in the automation when the application requires scrolling down or up to display additional information e.g. most of the e-commerce sites display only 10-20 products at a time and then load more products as the user scrolls down. In this tutorial, we’ll take an example of an e-commerce website – Flipkart and automate the scrolling in Selenium in order to fetch more results.

In this script, first, we will launch, write a search term and then scroll down to fetch more results corresponding to that search term. Automating page scrolling will make use of “scrollBy” method of javascript. For executing the javascript method we will use Javascript executor. The scrollBy method takes two parameters one each for horizontal and vertical scroll in terms of pixels.

JavascriptExecutor js = (JavascriptExecutor)driver;
js.executeScript("scrollBy(0, 2500)");

The following test script automates Flipkart’s scroll down functionality to test the display of new pages on the search result page as the user scrolls down.

public void testScroll() throws InterruptedException{

//Launch flipkart

//Write the search term - Buddha in search box
WebElement searchBox = driver.findElement("fk-top-search-box"));

//Click on searchButton
WebElement searchButton = driver.findElement(By.className("search-bar-submit"));;

//Inserting an optional wait of 3 seconds just to notice scroll down event

//Scroll down the webpage by 2500 pixels
JavascriptExecutor js = (JavascriptExecutor)driver;
js.executeScript("scrollBy(0, 2500)");

//Waiting till page:2 text is visible
WebElement pageNumberdisplayer = (new WebDriverWait(driver, 10)).until

//Verifying that page got scrolled  and "page-2" text is visible now
//and more products become visible
Assert.assertEquals(pageNumberdisplayer.getText(), "Page: 2");

That’s all we have in this post, please comment below if you have any questions. Check our complete step-step selenium tutorial here

Selenium Webdriver with Java – Complete Tutorial

От QA genius