How to scroll to element with Selenium WebDriver

merrua picture merrua · Feb 12, 2015 · Viewed 84.9k times · Source

How do I get Selenium WebDriver to scroll to a particular element to get it on the screen. I have tried a lot of different options but have had no luck. Does this not work in the C# bindings?

I can make it jump to a particular location ex

((IJavaScriptExecutor)Driver).ExecuteScript("window.scrollTo(0, document.body.scrollHeight - 150)");

But I want to be able to send it to different elements without giving the exact location each time.

public IWebElement Example { get { return Driver.FindElement(By.Id("123456")); } }

Ex 1)

((IJavaScriptExecutor)Driver).ExecuteScript("arguments[0].scrollIntoView(true);", Example);

Ex 2)

((IJavaScriptExecutor)Driver).ExecuteScript("window.scrollBy(Example.Location.X", "Example.Location.Y - 100)");

When I watch it, it does not jump down the page to the element, and the exception matches the element being off screen.

I added an bool ex = Example.Exists(); after it and checked the results. It does Exist (its true). Its not Displayed (as its still offscreen as it has not moved to the element) Its not Selected ??????

Someone is seeing success By.ClassName. Does anyone know if there is a problem with doing this By.Id in the C# bindings?

Answer

DRAX picture DRAX · Jul 6, 2015

Its little older question, but I believe that there is better solution than suggested above.

Here is original answer: https://stackoverflow.com/a/26461431/1221512

You should use Actions class to perform scrolling to element.

var element = driver.FindElement(By.id("element-id"));
Actions actions = new Actions(driver);
actions.MoveToElement(element);
actions.Perform();