How To Scroll Web Page In Selenium Webdriver Testing Script Using Java

If you want to implement scroll web page action automatically in your selenium testing script using java, you can use JavascriptExecutor class which is provided by selenium webdriver. You can run any JavaScript code use JavascriptExecutor class’s instance. In this article we will show you how to implement scroll action in selenium testing using java by examples.

Example 1
Scroll from webpage top to bottom using java, then click Next page link.

System.out.println("@Test method scrollToWebPageBottom started.");
 /* Navigate to the url */
 /* Cast webdriver object to Javascript Executor object,
 * then execute the javascript to go to the bottom. */
 ((JavascriptExecutor) driverObj).executeScript("window.scrollTo(0, document.body.scrollHeight)");
 System.out.println("@Test method scrollToWebPageBottom finished.");
 /* Thread sleep 2 seconds to let user to see the result */
 /* Create the by locator for the Next link in the bottom. */
 By nextPageCondition = By.xpath("//*[@class=\"next page-numbers\"]");
 /* Get the web element object for the Next link in the bottom. */
 WebElement nextPageElement = driverObj.findElement(nextPageCondition);
 /* Click the Next link.*/;
 /* When the next page load success, go to the bottom to see the result. 
 * Now we are in the second page.*/
 ((JavascriptExecutor) driverObj).executeScript("window.scrollTo(0, document.body.scrollHeight)");

Example 2
Scroll to the specific web element using java. We will scroll to the “Next ->” link in below java code example.

System.out.println("@Test method scrollToWebPageElemen started.");
 /* Navigate to */
 /* Get the Next page web element in the bottom use it's xpath. */
 WebElement element = driver.findElement(By.xpath("//*[@class=\"next page-numbers\"]"));
 /* Cast webdriver object to a Javascript Executor object, 
 * then use that object to run javascript to scroll to the web element. */
 ((JavascriptExecutor) driver).executeScript("arguments[0].scrollIntoView();", element);
 System.out.println("@Test method scrollToWebPageElemen finished.");

Example 3
Scroll to the particular position in the page using coordinates.

System.out.println("@Test method scrollWebpageByCoordinates started.");
 /* Navigate to */
 /* Cast webdriver object to a Javascript Executor object, then run the javascript to scroll to the position (0, 500)*/
 ((JavascriptExecutor) driver).executeScript("window.scrollBy(10,500)");
 System.out.println("@Test method scrollWebpageByCoordinates finished.");

[download id=”533″]

0 0 vote
Article Rating
Notify of

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

Inline Feedbacks
View all comments
Would love your thoughts, please comment.x