How to Scroll Down or UP a Page in Selenium Webdriver?

We can scroll down or up a page in Selenium webdriver using JavaScript Executor. Selenium can execute JavaScript commands with the help of the executeScript method.

To scroll down vertically in a page we have to use the JavaScript command window.scrollBy. Then pass the pixel values to be traversed along the x and y axis for horizontal and vertical scroll respectively.

The positive value set for x-axis shall scroll the page to the right while the negative value for x-axis shall scroll it to the left. Similarly, the positive value set for y-axis shall scroll down the page while the negative value for y-axis shall scroll up the page.


JavascriptExecutor j = (JavascriptExecutor)driver;


import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;
import java.util.concurrent.TimeUnit;
import org.openqa.selenium.JavascriptExecutor;
public class ScrollUpDown{
   public static void main(String[] args) {
      WebDriver driver = new FirefoxDriver();
      //implicit wait
      driver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS);
      //URL launch
      // scroll down by 500 pixels with Javascript Executor
      JavascriptExecutor j = (JavascriptExecutor) driver;
      // identify element
      WebElement m = driver.findElement(By.linkText("Latest Courses"));
      String s = m.getText();
      System.out.println("Text obtained on scrolling down: "+ s);
      // scroll down up 500 pixels with Javascript Executor
      // identify element
      WebElement n = driver.findElement(By.tagName("h4"));
      String r = n.getText();
      System.out.println("Text obtained on scrolling up: "+ r);


Updated on: 06-Apr-2021

8K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started