Reputation: 549
Hi there I'm using this code to try and scroll the page until element is in the DOM. However it the page doesn't scrol, it just loops and loops over. Is my IJavaScriptExecutor
wrong?
public static void ScrollUntilElementinDom(this IWebDriver driver, By by)
{
bool isPresent = false;
while (isPresent == false)
{
try
{
isPresent = driver.FindElement(by).Displayed;
}
catch (Exception)
{
}
if (isPresent == true)
{
break;
}
else
{
((IJavaScriptExecutor) driver).ExecuteScript("window.scrollBy(100,0);");
}
}
Upvotes: 0
Views: 1006
Reputation: 50919
Try to scroll with Actions
Actions action = new Actions(driver);
action.MoveToElement(driver.FindElement(by)).Build().Perform();
And to find if the element is displayed you can use explicit wait
WebDriverWait wait = new WebDriverWait(driver, TimeSpan.FromSeconds(15));
try
{
wait.Until(ExpectedConditions.ElementIsVisible(by));
isPresent = true;
}
catch (Exception) { }
This will wait up to 15 seconds for the element to be visible.
Upvotes: 1
Reputation: 3196
You should use Actions class to perform scrolling to element.
WebElement element = driver.findElement(By.id("element-id"));
Actions actions = new Actions(driver);
actions.moveToElement(element);
actions.perform();
Upvotes: 0
Reputation: 35653
You need to wait for the content to load.
At no point are you waiting. Consider WebDriverWait
Upvotes: 2