Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Scroll the page almost to the end in Selenium

Tags:

c#

selenium

I need scrool page in Selenium almost to the end of page (150 px until bottom). But my code doesn't work. It's scroll to bottom. How it's fix?

IWebElement element = (IWebElement)((IJavaScriptExecutor)driver).ExecuteScript("javascript:window.scrollBy(0,document.body.scrollHeight-150)");
like image 319
titans Avatar asked Sep 16 '13 16:09

titans


2 Answers

Try this:

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

A few notes:

  • You are executing a command to scroll, which does not return an IWebElement, so there is no need to have the IWebElement element = part.
  • You don't need the javascript: part either
  • Since you want to scroll to an absolute position, scrollTo is a better fit
like image 85
prestomanifesto Avatar answered Sep 22 '22 06:09

prestomanifesto


You can scroll to the necessary location using javascript's scrollTo method.

public void scrollToElement(By by) {
  Locatable element = (Locatable) selenium.findElement(by);
  Point p= element.getCoordinates().getLocationOnScreen();
  JavascriptExecutor js = (JavascriptExecutor) selenium;  
  js.executeScript("window.scrollTo(" + p.getX() + "," + (p.getY()) + ");");
}
like image 38
Nilanjan Saha Avatar answered Sep 22 '22 06:09

Nilanjan Saha