What is the best way to scroll to a web element located on the current page within the viewport using Selenium

Janani Ayeshika :

I am new to the automation and I would like to know how to scroll to a web element on the current page using selenium and java.

I have tries many methods which is described in stackoverflow. But couldn't able to solve my problem.

Solutions I tried:

WebElement element = driver.findElement(By.id("id_of_element"));
((JavascriptExecutor) driver).executeScript("arguments[0].scrollIntoView(true);", element);
Thread.sleep(500);
Osanda Deshan :

You can use Actions class provided by Selenium.

public void scrollToElement(WebElement element){
    Actions actions = new Actions(driver);
    actions.moveToElement(element);
    actions.perform();
    WebDriverWait wait = new WebDriverWait(driver, 60);
    wait.until(ExpectedConditions.visibilityOf(element));
}

Here I have added an explicit wait and it will wait until the web element is visible. Maximum waiting time will be 60 seconds. If the web element is not visible within 60 seconds, this will throw an exception. You can increase the waiting time by changing this line.

WebDriverWait wait = new WebDriverWait(driver, 60);

Hope this helps.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=93321&siteId=1