Learn Selenium and Java for Selenium

Saturday, 16 April 2016

Scroll into View in Selenium

Scroll down to a view on a webpage in Selenium

How selenium supports scrolling down on a page?

Consider a web application, some times some text is visible towards bottom of a page so we need to scroll down to a page to see the text

Selenium provides JavaScript Executor interface which will allow to execute Java Script from Selenium Script

Scroll Down a Page 

The following code will scroll down to page of Wikipedia until the text "On this day..." element is visible

 import java.io.File;  
 import java.io.IOException;  
 import org.apache.commons.io.FileUtils;  
 import org.openqa.selenium.By;  
 import org.openqa.selenium.JavascriptExecutor;  
 import org.openqa.selenium.OutputType;  
 import org.openqa.selenium.TakesScreenshot;  
 import org.openqa.selenium.WebDriver;  
 import org.openqa.selenium.WebElement;  
 import org.openqa.selenium.chrome.ChromeDriver;  
 import org.openqa.selenium.firefox.FirefoxDriver;  
 import org.testng.annotations.Test;  
      public class Scroll{  
           public static void main(String[] args) throws IOException, InterruptedException {  
                WebDriver a= new FirefoxDriver();  
                a.manage().window().maximize();  
                a.get("https://en.wikipedia.org/wiki/Main_Page");  
                JavascriptExecutor je = (JavascriptExecutor)a;  
                WebElement c= a.findElement(By.xpath(".//*[@id='On_this_day...']"));  
                je.executeScript("arguments[0].scrollIntoView(true);",c);  
                System.out.println(c);  
             a.quit();  
                }  
           }  



Notes

1- As JavascriptExecutor is interface we cannot create an object for this, we have typecast(downcasting) it with webdriver reference which is "a"
2- ScrollIntoView(true) :- It will scroll until element is not visible, once it is visible it will stop scrolling
3- executeScript("arguments[0].scrollIntoView(true);",c); :-This is a javascript code and here the code will keep on scrolling the page until the element present on "c" reference variable is not visible

Output









0 comments:

Post a Comment

Popular Posts

Recent Posts



Newsletter

Join our newsletter to get secret tips directly in your inbox!


*We Hate Spam!

Powered by Blogger.