Syntax error How to perform scrolling action on page in Selenium?

How to perform scrolling action on page in Selenium?



We can perform the following actions with respect to scrolling in Selenium −

Vertical scrolling

The scrolling down to a specific pixel.

JavascriptExecutor j = (JavascriptExecutor) driver;
// scroll down by 1500 pixel with coordinates 0 and 1500 in x, y axes
j.executeScript("window.scrollBy(0,1500)");

The scrolling down to the bottom of the page.

JavascriptExecutor j = (JavascriptExecutor) driver;
// scroll down the bottom of page
js.executeScript("window.scrollTo(0, document.body.scrollHeight)");

Example

For vertical scroll down till the element is visible.

import org.openqa.selenium.By;
import org.openqa.selenium.Keys;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import java.util.concurrent.TimeUnit;
import org.openqa.selenium.JavascriptExecutor;
public class ScrollDownVisible {
   public static void main(String[] args) {
      System.setProperty("webdriver.chrome.driver", "C:\Users\ghs6kor\Desktop\Java\chromedriver.exe");
      WebDriver driver = new ChromeDriver();
      String url = "https://www.tutorialspoint.com/index.htm";
      driver.get(url);
      driver.manage().timeouts().implicitlyWait(12, TimeUnit.SECONDS);
      JavascriptExecutor js = (JavascriptExecutor) driver;
      WebElement terms = driver.findElement(By.linkText("Terms of use”));
      // scroll down the web element for viewing
      js.executeScript("arguments[0].scrollIntoView();",terms);
      driver.close();
   }
}

Horizontal scrolling

Example

For horizontal scroll on page.

import org.openqa.selenium.By;
import org.openqa.selenium.Keys;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import java.util.concurrent.TimeUnit;
import org.openqa.selenium.JavascriptExecutor;
public class HScrollDown {
   public static void main(String[] args) {
      System.setProperty("webdriver.chrome.driver", "C:\Users\ghs6kor\Desktop\Java\chromedriver.exe");
      WebDriver driver = new ChromeDriver();
      String url = "https://www.tutorialspoint.com/index.htm";
      driver.get(url);
      driver.manage().timeouts().implicitlyWait(12, TimeUnit.SECONDS);
      JavascriptExecutor js = (JavascriptExecutor) driver;
      WebElement meets = driver.findElement(By.linkText("NetMeeting”));
      // scroll down the web element for viewing
      js.executeScript("arguments[0].scrollIntoView();", meets);
      driver.close();
   }
}
Updated on: 2020-06-10T13:44:08+05:30

1K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements