How to scroll a Web Page using coordinates of a WebElement in Selenium WebDriver?

SeleniumAutomation TestingTesting Tools

We can scroll a webpage using coordinates of a webelement in Selenium webdriver using the JavaScript Executor. Selenium executes JavaScript commands with the help of the executeScript method.

To get the unique coordinates of an element we shall create an object of the class Point which shall store the location of the webelement obtained from the getLocation method.

Then the individual x and y coordinate values can be computed from the getX and the getY methods respectively. Finally, to actually perform scroll upto the coordinates of an element, the command window.scrollBy(x coordinate, y coordinate) is passed as a parameter to the executeScript method.

Syntax

(JavascriptExecutor)
driver).executeScript("window.scrollBy(100,150)");

here, 100 and 150 are the x and y coordinates respectively.

Example

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;
import java.util.concurrent.TimeUnit;
import org.openqa.selenium.Point;
import org.openqa.selenium.JavascriptExecutor;
public class ScrollWithCodrdnts{
   public static void main(String[] args) {
      System.setProperty("webdriver.gecko.driver",
         "C:\\Users\\ghs6kor\\Desktop\\Java\\geckodriver.exe");
      WebDriver driver = new FirefoxDriver();
      //implicit wait
      driver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS);
      //URL launch
      driver.get("https://www.tutorialspoint.com/index.htm");
      //identify element
      WebElement n = driver.findElement(By.linkText("Latest Courses"));

      //obtain element x, y coordinates with getLocation method
      Point p = n.getLocation();
      int X = p.getX();
      int Y = p.getY();
      //scroll with Javascript Executor
      JavascriptExecutor j = (JavascriptExecutor) driver;
      j.executeScript("window.scrollBy(" + X + ", " + Y + ");");
      System.out.println("Text is: " + n.getText());
      driver.quit();
   }
}

Output

raja
Published on 06-Apr-2021 08:58:20
Advertisements