Scrolling in Selenium

Scrolling in Selenium Webdriver

Last updated on

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 filpkart.com, 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.

@Test
public void testScroll() throws InterruptedException{
		
	//Launch flipkart
	driver.get("http://www.flipkart.com");
				
	//Write the search term - Buddha in search box
	WebElement searchBox = driver.findElement(By.id("fk-top-search-box"));
	searchBox.sendKeys("Buddha");
			
	//Click on searchButton
	WebElement searchButton = driver.findElement(By.className("search-bar-submit"));
	searchButton.click();
	
	//Inserting an optional wait of 3 seconds just to notice scroll down event
	Thread.sleep(3000);
	
	//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
          (ExpectedConditions.presenceOfElementLocated(By.cssSelector("div.row")));
	
	//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

1 thought on “Scrolling in Selenium Webdriver”

Leave a Comment