Thursday, 24 September 2015

Page scrolling using Selenium


Scrolling a webpage is required in 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 example of flipkart website and automate the scrolling of webpage in order to fetch more results.
In automation 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)");

Following test script automates flipkart's scroll down functionality to test 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");
   
}

                  

No comments:

Post a Comment