Scroll Element into View with Selenium.


We may need to perform action on an element which is not present in the viewable area of the page. We need to scroll down to the page in order to reach that element.

Selenium cannot perform scrolling action directly. This can be achieved with the help of Javascript Executor and Actions class in Selenium. DOM can work on all elements on the web page with the help of Javascript.

Selenium can execute commands in Javascript with the help of the execute_script() method. For the Javascript solution, we have to pass true value to the method scrollIntoView() to identify the object below our current location on the page. We can execute mouse movement with the help of the Actions class in Selenium.

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 ScrollToViewJs{
   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);
      // identify element
      WebElement l=driver.findElement(By.xpath("//*[text()='ABOUT US']"));
      // Javascript executor
      ((JavascriptExecutor)driver).executeScript("arguments[0].scrollIntoView(true);", l);
      Thread.sleep(800);
      driver.quit();
   }
}

While working with Actions class to scroll to view, we have to use the moveToElement() method. This method shall perform mouse movement till the middle of the element.

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 ScrollToViewActions{
   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);
      // identify element
      WebElement l=driver.findElement(By.xpath("//*[text()='ABOUT US']"));
      // Actions class with moveToElement()
      Actions a = new Actions(driver);
      a.moveToElement(l);
      a.perform();
      driver.quit();
   }
}

Output

Updated on: 31-Oct-2023

20K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements