How to Scroll Down a Page in Selenium Webdriver Java

Selenium is an open-source web-based automation tool that is implemented using a web driver. We will be using geckodriver because Selenium 3 enables geckodriver as the default WebDriver implementation for Firefox.

Pre-requisites:

  1. geckodriver.exe
  2. maven dependency selenium
 <dependency>
    <groupid>org.seleniumhq.selenium</groupid>
	<artifactid>selenium-java</artifactid>  
	<version>4.1.1</version> 
 </dependency>

Steps:

it's a 6 steps process:

  1. Set webdriver.gecko.driver and its' path as a system property.
  2. Set the firefox diver.
  3. Typecast web driver as Javascript executor. 
  4. Browse the website.
  5. Set x and y coordinates for scrolling.
    • x: Horizontal scroll 
    • y: Vertical scroll 
    • +ve: scroll up 
    • -ve: scroll down
  6. Execute the script using the javascript executor.
Let’s see all the above steps in the code. We will use window.scrollBy(x,y) function to set coordinates of the page scroll.
import org.openqa.selenium.By;
import org.openqa.selenium.JavascriptExecutor;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;

public class ScrollDown {

    public static String GECKODRIVER_PATH = "F:\\WORK\\SeleniumShortTasks\\Scroll\\src\\main\\resources\\geckodriver.exe";

    public static void main(String[] args) {
        //set firefox webdriver & JS executor
        System.setProperty("webdriver.gecko.driver", GECKODRIVER_PATH);
        WebDriver driver = new FirefoxDriver();
        JavascriptExecutor js = (JavascriptExecutor) driver;

        //get the firefox browser & Browse the Website
        String siteLink = "https://en.wikipedia.org/wiki/Selenium";
        driver.get(siteLink);

        //run a script : to scroll the window
        js.executeScript("window.scrollBy(0,1000)", "");
        //Horizontal : 0 px
        //Vertical : 1000 px.
        // To scroll up use -1000

    }
}

Output:

 
All resources used in this tutorial are attached:
  • source code
  • geckdriver.exe
Download

Comments