Scrolling to element using Webdriver.


We can perform scrolling to an element using Selenium webdriver. This can be achieved in multiple ways. Selenium cannot handle scrolling directly. It takes the help of the Javascript Executor and Actions class to do scrolling action.

First of all we have to identify the element up to which we have to scroll to with the help of any of the locators like class, id, name and so on. Next we shall take the help of the Javascript Executor to run the Javascript commands. The method executeScript is used to execute Javascript commands in Selenium. We have to use the scrollIntoView method in Javascript and pass true as an argument to the method.

Syntax

WebElement e = driver.findElement(By.name("name"));
((JavascriptExecutor) driver).executeScript("arguments[0].scrollIntoView(true);", e);

Example

Code Implementation with Javascript Executor.

import org.openqa.selenium.By;
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 ScrollToElementJs{
   public static void main(String[] args) {
      System.setProperty("webdriver.chrome.driver", "C:\Users\ghs6kor\Desktop\Java\chromedriver.exe");
      WebDriver driver = new ChromeDriver();
      driver.get("https://www.tutorialspoint.com/index.htm");
      driver.manage().timeouts().implicitlyWait(12, TimeUnit.SECONDS);
      // identify element
      WebElement m=driver.findElement(By.xpath("//*[text()='Careers']"));
      // Javascript executor
      ((JavascriptExecutor)driver).executeScript("arguments[0].scrollIntoView (true);", m);
      Thread.sleep(200);
      driver.close();
   }
}

With the Actions class, we shall use the moveToElement method and pass the webelement locator as an argument to the method.

Example

Code Implementation with Actions.

import org.openqa.selenium.By;
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.interactions.Action;
import org.openqa.selenium.interactions.Actions;
public class ScrollToElementActions{
   public static void main(String[] args) {
      System.setProperty("webdriver.chrome.driver", "C:\Users\ghs6kor\Desktop\Java\chromedriver.exe");
      WebDriver driver = new ChromeDriver();
      driver.get("https://www.tutorialspoint.com/index.htm");
      driver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS);
      // identify element
      WebElement m=driver.findElement(By.xpath("//*[text()='Careers']"));
      // moveToElement method with Actions class
      Actions act = new Actions(driver);
      act.moveToElement(m);
      act.perform();
      driver.close();
   }
}

Output

Updated on: 26-Oct-2020

185 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements