3

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);
undetected Selenium
  • 183,867
  • 41
  • 278
  • 352
  • 2
    You should point to the solutions you tried and explain why they didn't work for you; preferably with a [mcve]. – Slaw Dec 28 '18 at 04:29

3 Answers3

4

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.

Osanda Deshan
  • 1,473
  • 3
  • 14
  • 30
0

To scroll a WebElement on the current page within the Viewport using Selenium and Java you need to induce WebDriverWait for the visibility of element located and you can use the following solution:

WebElement element = new WebDriverWait(driver, 20).until(ExpectedConditions.visibilityOfElementLocated(By.id("id_of_element")));
((JavascriptExecutor) driver).executeScript("arguments[0].scrollIntoView();", element)
undetected Selenium
  • 183,867
  • 41
  • 278
  • 352
0

You're passing that element from javascript to java and back to javascript. That's a bad idea, by the time it makes that round trip it might not be there anymore.

((JavascriptExecutor) driver).executeScript("document.querySelector('#id_of_element').scrollIntoView(true);");

Also, a lot of things that you needed to scroll into view for (with older seleniums), you no longer do.

pguardiario
  • 53,827
  • 19
  • 119
  • 159
  • can you provide here the way to scroll if the locator strategy is in xpath? I think it would be more helpful – Osanda Deshan Dec 29 '18 at 04:31
  • And I think when you are passing true in scrollIntoView() it will scroll down only. If the element is on the top of the page this might get failed. – Osanda Deshan Dec 29 '18 at 04:34
  • You would need to translate the xpath to css. Arguments to scrollIntoView affect alignment and behavior. – pguardiario Dec 29 '18 at 07:12