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:
- geckodriver.exe
- 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:
  
  
  - 
      Set webdriver.gecko.driverand its'pathas a system property.
- Set the firefox diver.
- Typecast web driver as Javascript executor.
- Browse the website.
- Set x and y coordinates for scrolling.
- x: Horizontal scroll
- y: Vertical scroll
- +ve: scroll up
- -ve: scroll down
- 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:
- source code
- geckdriver.exe

Comments
Post a Comment