How To Scroll a Page Using Selenium WebDriver with Java?

How To Scroll a Page Using Selenium WebDriver with Java?

Automating an application can be performed in various ways with a variety of tools. Because it is free and simple to use, Selenium WebDriver is the most popular of those. Selenium WebDriver gives users a lot of flexibility to write their test in different programming language and allow the user to execute their test on different browser like Firefox, Chrome, Edge, Safari, etc

Let’s understand why scrolling is important. 

Scrolling is one of the most important features of any application. You will not find any website which does not have scrolling capability. It’s almost impossible to display all the content in a single frame, users need to scroll down or up to get all the content of the application. 

QAs are responsible to create robust tests and deliver bug-free application. They must specifically make sure that every UI element is operating as intended. 

Selenium WebDriver directly interacts with the DOM, and several operations can be carried out without the need to scroll. However, there are rare instances where specific web elements are only accessible after the user scrolls to the element. In these situations, automating the scrolling process is required.

This article will help you to understand horizontal and vertical scroll operations with Selenium WebDriver.

Starting your journey with Selenium WebDriver? Check the article on Selenium WebDriver.

In Selenium, scrolling can be handled by using JavaScriptexecutor. JavaScriptexecutor is an interface that is used to execute JavaScript through selenium webdriver. The JavaScript Executor is a powerful feature of Selenium WebDriver that allows you to execute JavaScript code directly in the browser.

JavaScriptexecutor provides two methods:

  1. ExecuteScript
  2. ExecutrAsyncScript

Syntax

ScrollBy is a JavaScriptexecutor method that accepts two parameters x and y, which defines horizontal and vertical axes.

Now let’s discuss the Scroll operation in different scenarios:

  1. How do I scroll down to the page’s bottom using Selenium?
  2. How do I scroll based on the visibility of the Web element on the page in Selenium?
  3. How does Selenium scroll a webpage both horizontally and vertically?
  4. How do you scroll a webpage with infinite scrolling using Selenium?
  5. How do you Scroll to the top of the page in Selenium?
  6. How do you scroll down in a page by specified pixels in Selenium?

How do I scroll down to the page’s bottom using Selenium?

In Selenium, you can use the JavaScript Executor to scroll down to the bottom of a web page. You can use the “scrollTo” method to scroll to the bottom of the page. The following code snippet shows an example of how to scroll down to the bottom of a web page using Selenium in Java:

JavaScriptexecutor js = (JavascriptExecutor) driver; js.executeScript(“window.scrollTo(0, document.body.scrollHeight)”);

In the above example, the JavaScript Executor is first cast to a JavascriptExecutor object and then the “executeScript” method is used to execute a JavaScript code. The JavaScript code passed to the “executeScript” method is “window.scrollTo(0, document.body.scrollHeight)”, which scrolls the page to the bottom.

Code snippet:

import java.util.concurrent.TimeUnit; import org.openqa.selenium.By; import org.openqa.selenium.JavascriptExecutor; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; import org.openqa.selenium.chrome.ChromeDriver; public class ScrollDown { public static void main(String[] args) { //specify the location of the driver System.setProperty(“webdriver.chrome.driver”,”ChromeDriver_path”); //Initialising the driver WebDriver driver = new ChromeDriver(); //launch the application driver.get(“https://opensource-demo.orangehrmlive.com/web/index.php/auth/login”); //maximize the browser driver.manage().window().maximize(); //It will wait for maximum of 10sec for each object driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS); //Identify username field using xpath as locator WebElement username = driver.findElement(By.xpath(“//input[@placeholder=’Username’]”)); // Identify password field using xpath as locator WebElement password = driver.findElement(By.xpath(“//input[@placeholder=’Password’] “)); //Enter the value of the username username.sendKeys(“Admin”); //Enter the value of the password password.sendKeys(“admin123”); //identify the locator of the login button and click on Login btn driver.findElement(By.id(“btnLogin”)).click(); JavascriptExecutor js = (JavascriptExecutor) driver; //It will help you to get the height of the page and helps to scroll to the bottom of the page js.executeScript(“window.scrollTo(0, document.body.scrollHeight)”); driver.close(); } }

Above code snippet will help you to scroll your page to the bottom of the page.

How do I scroll based on the visibility of the Web element on the page in Selenium?

Before you perform scroll operations in selenium, it is necessary that the corresponding web element is present under DOM.

ScrollIntoView() method will help you to scroll to the desired element.

The scrollIntoView() method is a JavaScript method that can be used to scroll an HTML element into the viewport. When called on an element, it will scroll the element’s parent container so that the element becomes visible in the viewport.

JavascriptExecutor js = (JavascriptExecutor) driver; js.executeScript(“arguments[0].scrollIntoView();”, webElement);

Code snippet:

package demo; import java.util.concurrent.TimeUnit; import org.openqa.selenium.By; import org.openqa.selenium.JavascriptExecutor; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; import org.openqa.selenium.chrome.ChromeDriver; public class ScrollIntoTheView { public static void main(String[] args) { //specify the location of the driver System.setProperty(“webdriver.chrome.driver”,”ChromeDriver_path”); //Initialising the driver WebDriver driver = new ChromeDriver(); //launch the website driver.get(“https://testsigma.com/”); //maximize the window to full screen driver.manage().window().maximize(); //It will wait for maximum of 10sec for each object driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS); JavascriptExecutor js = (JavascriptExecutor) driver; //Identify the xpath of the object. WebElement element = driver.findElement(By.xpath(“//span[text()=’Sign up for free’]”)); //scrollIntoView will help us to scroll to the Sign-up button js.executeScript(“arguments[0].scrollIntoView();”, element); driver.close(); } }

How does Selenium scroll a webpage both horizontally and vertically?

In Selenium, you can use the JavaScript Executor to scroll a web page both horizontally and vertically. However, the JavaScript Executor does not have the method to scroll a web page both horizontally and vertically. It has the method “scrollBy” and “scrollTo” which can scroll the page horizontally or vertically.

In order to scroll the page both horizontally and vertically, you need to use the “scrollBy” method twice in a row, once for horizontal scrolling and once for vertical scrolling. Here is an example of how to use the “scrollBy” method to scroll a web page both horizontally and vertically in Selenium: 

Code snippet:

For Horizontal Scroll


package demo; import java.util.concurrent.TimeUnit; import org.openqa.selenium.JavascriptExecutor; import org.openqa.selenium.WebDriver; import org.openqa.selenium.chrome.ChromeDriver; public class HorizontalScroll { public static void main(String[] args) { //specify the location of the driver System.setProperty(“webdriver.chrome.driver”,”ChromeDriver_path”); //Initialising the driver WebDriver driver = new ChromeDriver(); //launch the website driver.get(“https://www.album.alexflueras.ro/index.php”); //maximize the window to full screen driver.manage().window().maximize(); //It will wait for maximum of 10sec for each object driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS); JavascriptExecutor js = (JavascriptExecutor) driver; js.executeScript(“window.scrollBy(5000,40)”); driver.close(); } }

For Vertical Scroll


package demo; import java.util.concurrent.TimeUnit; import org.openqa.selenium.JavascriptExecutor; import org.openqa.selenium.WebDriver; import org.openqa.selenium.chrome.ChromeDriver; public class VerticalScroll { public static void main(String[] args) { //specify the location of the driver System.setProperty(“webdriver.chrome.driver”,”ChromeDriver_path”); //Initialising the driver WebDriver driver = new ChromeDriver(); //launch the website driver.get(“https://www.album.alexflueras.ro/index.php”); //maximize the window to full screen driver.manage().window().maximize(); //It will wait for maximum of 10sec for each object driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS); JavascriptExecutor js = (JavascriptExecutor) driver; js.executeScript(“window.scrollBy(40,3000)”); //vertical scroll driver.close(); } }

How do you scroll a webpage with infinite scrolling using Selenium?

In today’s world, most applications implement infinite scrolling. Since users do not have to do the time-consuming operation of pressing the “Previous” and “Next” buttons, pages with endless scrolling may see improved engagement.

You can visit https://the-internet.herokuapp.com/infinite_scroll to look at infinite scrolling. 

Code snippet

package demo; import java.util.concurrent.TimeUnit; import org.openqa.selenium.JavascriptExecutor; import org.openqa.selenium.WebDriver; import org.openqa.selenium.chrome.ChromeDriver; public class InfiniteScrolling { public static void main(String[] args) { //specify the location of the driver System.setProperty(“webdriver.chrome.driver”, “ChromeDriver_path”); //Initialising the driver WebDriver driver = new ChromeDriver(); //launch the website driver.get(“https://www.album.alexflueras.ro/index.php”); //maximize the window to full screen driver.manage().window().maximize(); //It will wait for maximum of 10sec for each object driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS); JavascriptExecutor js = (JavascriptExecutor) driver; long intialLength = (long) js.executeScript(“return document.body.scrollHeight”); while(true){ js.executeScript(“window.scrollTo(0,document.body.scrollHeight)”); try { Thread.sleep(3000); } catch (InterruptedException e) { e.printStackTrace(); } long currentLength = (long) js.executeScript(“return document.body.scrollHeight”); if(intialLength == currentLength) { break; } intialLength = currentLength; } } }

How do you Scroll to the top of the page in Selenium?

In the above article, we have seen scrolling down or scrolling horizontally but scrolling to the top of the page is one of the widely used operations on pages using the JavascriptExecutor interface. 

To demonstrate this, we first need to scroll down to the page using selenium and then scroll up to the page.

There are various ways to scroll to the top of the page. 

Method 1: 

package demo; import java.util.concurrent.TimeUnit; import org.openqa.selenium.By; import org.openqa.selenium.JavascriptExecutor; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; import org.openqa.selenium.chrome.ChromeDriver; public class ScrollUp { public static void main(String[] args) { //specify the location of the driver System.setProperty(“webdriver.chrome.driver”,”ChromeDriver_path”); //Initialising the driver WebDriver driver = new ChromeDriver(); //launch the website driver.get(“https://www.album.alexflueras.ro/index.php”); //maximize the window to full screen driver.manage().window().maximize(); //It will wait for maximum of 10sec for each object driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS); WebElement username = driver.findElement(By.xpath(“//input[@placeholder=’Username’]”)); WebElement password = driver.findElement(By.xpath(“//input[@placeholder=’Password’] “)); username.sendKeys(“Admin”); password.sendKeys(“admin123”); WebElement loginBtn = driver.findElement(By.id(“btnLogin”)); loginBtn.click(); JavascriptExecutor js = (JavascriptExecutor) driver; js.executeScript(“window.scrollTo(0, document.body.scrollHeight)”); try { Thread.sleep(3000); } catch (InterruptedException e) { e.printStackTrace(); } js.executeScript(“window.scrollTo(document.body.scrollHeight,0)”); driver.close(); } }

How do you scroll down a page by specified pixels in Selenium?

With the help of JavaScriptExecutor, you can scroll to a particular point by specifying the exact pixel or coordinates of the object. This can be achieved by using the ‘ScrollBy’ function.in JavaScript. 

Code Snippet:

package demo; import java.util.concurrent.TimeUnit; import org.openqa.selenium.JavascriptExecutor; import org.openqa.selenium.WebDriver; import org.openqa.selenium.chrome.ChromeDriver; public class ScollByPixel { public static void main(String[] args) { //specify the location of the driver System.setProperty(“webdriver.chrome.driver”,”ChromeDriver_path”); //Initialising the driver WebDriver driver = new ChromeDriver(); //launch the website driver.get(“https://www.album.alexflueras.ro/index.php”); //maximize the window to full screen driver.manage().window().maximize(); //It will wait for maximum of 10sec for each object driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS); JavascriptExecutor js = (JavascriptExecutor) driver; //specify the number of pixels the page must be scrolled js.executeScript(“window.scrollBy(0,3000)”); driver.close(); } }

Stay up to date with such resourceful blogs,

subscribe to our monthly newsletter

Join our QA Community

Conclusion

In the above article, we have seen different ways of scrolling on a web page using Selenium with Java. One of the frequently performed tasks when it comes to Selenium automation testing is automating the page scroll action utilizing the JavaScriptExecutor interface. We have seen sample code for scrolling down, scrolling up, scrolling horizontally and vertically, etc. Do share your thoughts on how you have implemented scrolling a web page in your scripts. 

Do share this blog with your friends and colleagues. 

Happy testing 😊

Frequently Asked Question

How do I scroll down using sendKeys in selenium?

In Selenium, you can use the sendKeys() method to simulate key presses, including the “Page Down” key. To scroll down using sendKeys(), you can use the following code:

This will simulate a “Page Down” key press on the element, which will scroll the element down.

How do I scroll down a page using Java by specified pixels in Selenium?

In Selenium using Java, you can use the JavascriptExecutor class to execute JavaScript code that can scroll the scroll bar on a page. Here is an example of how you can scroll the scroll bar down by a certain number of pixels:

JavascriptExecutor js = (JavascriptExecutor) driver; js.executeScript(“window.scrollBy(0,1000)”);

This will scroll down the web page by 1000 pixels. You can adjust the number of pixels to scroll by as needed.


Test automation made easy

Start your smart continuous testing journey today with Testsigma.

SHARE THIS BLOG

RELATED POSTS


Power of POC in Testing: Your Exclusive Guide to Success
Power of POC in Testing: Your Exclusive Guide to Success
performance testing tools_banner image
Test objects in software testing | Types & How to Create it?
How To Write Calculator Test Cases With Sample Test Cases
How To Write Calculator Test Cases? With Sample Test Cases