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, 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
        //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");


No comments:

Post a Comment

What is Wireframe ?

    A wireframe is a layout of a web page that demonstrates what interface elements will exist on key pages. It is a criti...