Using Selenium to Scroll on pages

By using selenium to scroll on pages, you can do automated testing of a page which is dynamically loaded. Something like linkedin or facebook where you get the updates as you scroll down the page. To scroll throught the page in Selenium you can use JavaScript function called scrollBy. Here is the code for it.

for (int x= 0;; x++) {
 ifx >=60){
 break;
 }
 driver.executeScript("window.scrollBy(0,200)", "");
 Thread.sleep(1000);
 }

The above code uses the JavaScript method “scrollBy” to scroll on the page. The for loop runs for 60 sec and calls the scrollBy function every second. This makes the selenium to scroll on the page.
If you have a test where you need to scroll on the page and check whether an element is loaded dynamically or not you can put a isElementPresent like function after the “driver.executeScript” to check visibility of your element.

Following code snippet shows the above function in linkedin.

package Sample;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.ie.InternetExplorerDriver;
import org.openqa.selenium.remote.RemoteWebDriver;
import org.testng.annotations.Test;
import org.testng.annotations.BeforeSuite;
import org.testng.annotations.AfterSuite;
public class ScrollingSample {
 public RemoteWebDriver driver;
 @Test
 public void ScrollTest() throws InterruptedException {
 driver.get("http://www.linkedin.com");
 driver.findElement(By.id("session_key-login")).click();
 driver.findElement(By.id("session_key-login")).clear();
 driver.findElement(By.id("session_key-login")).sendKeys("xxxx@xxx.xxx");
 driver.findElement(By.id("session_password-login")).clear();
 driver.findElement(By.id("session_password-login")).sendKeys("xxxxx");
 driver.findElement(By.id("signin")).click();

//Following is the code that scrolls through the page
 for (int second = 0;; second++) {
 if(second >=60){
 break;
 }
 driver.executeScript("window.scrollBy(0,200)", "");
 Thread.sleep(3000);
 }
 }
@BeforeSuite(alwaysRun = true)
 public void beforeSuite() {
 driver = new InternetExplorerDriver(); 

 }
>@AfterSuite(alwaysRun = true)
 public void afterSuite() {
 driver.quit();
 }
}

Note: You can use similar approach and use other Javascript functions.

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.