Hi Piyush, if you want to scroll a webpage using coordinates of an element, then you first need to locate the element and find its location. Then from location, you can get the X and Y coordinates, which you can pass in scrollBy method:
import java.util.concurrent.TimeUnit;
import org.openqa.selenium.By;
import org.openqa.selenium.JavascriptExecutor;
import org.openqa.selenium.Point;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.testng.annotations.BeforeTest;
import org.testng.annotations.Test;
public class ScrollTest {
WebDriver driver;
@BeforeTest
public void setUp() {
System.setProperty("webdriver.chrome.driver", "C:\\Users\\Anvi_R\\chromedriver.exe");
driver = new ChromeDriver();
}
@Test
public void test01() throws InterruptedException {
driver.get("https://www.edureka.co");
driver.manage().window().maximize();
driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);
WebElement viewAllCoursesBtn = driver.findElement(By.xpath("//section[5]//article[1]//div[1]//span[2]//a[1]"));
Point point = viewAllCoursesBtn.getLocation();
int x_coordinate = point.getX();
int y_coordinate = point.getY();
scrollToElement(x_coordinate, y_coordinate);
}
public void scrollToElement(int x, int y) {
JavascriptExecutor javScriptExecutor = (JavascriptExecutor) driver;
javScriptExecutor.executeScript("window.scrollBy(" + x + ", " + y + ");");
}
}