Selenium webdriver works on DOM so it not always needs scroll bar to locate the objects, but there are certain instances where the object becomes visible only after scrolling. In these situations we need to scroll through the webpage to perform any action on the objects.
4) To scroll Up,Down , Left and Right from current Location :
There could be 2 types of scrolling : Horizontal and Vertical
To achieve the horizontal and vertical scrolling we use javascriptexecutor in Selenium. The scrolling is done based on pixels which is given as parameter..
The syntax is as below :
JavascriptExecutor js = (JavascriptExecutor) driver; js.executeScript(Script,Arguments);
There are different situations in which we need different types of scrolling . They are :
1) To scroll to a particular position by giving the exact pixels in the parameters :
JavascriptExecutor js = (JavascriptExecutor) driver; js.executeScript(Window.ScrollBy(400,500)");
The above command will scroll the window to 400 Horizontal(x-pixels) and 500 vertical(y-pixels) pixels.
Note: If we want to scroll only horizontally or vertically then we can give that location only and keep the other one as zero. we can give the argument as :
Window.scrollBy(0,500) - to scroll 500 pixel vertically
2) To scroll on a webpage till a element becomes visible and can be located
//Give the locator of the "Element" present on the webpage WebElement Element = driver.findElement(By.name("ABCD")); //Now scroll on the window till the element is found js.executeScript("arguments[0].scrollIntoView();", Element);
Here we locate the element which has to be found on webpage by a unique locator. Then we use the given argument in the javascriptexecutor. It will keep on scrolling till the element is found.
Note : This can be done horizontally or vertically till the element is found
3) To scroll till the end of the page
JavascriptExecutor js = (JavascriptExecutor) driver; js.executeScript(Window.ScrollTo(0,document.body.scrollheight)");
This command will keep on scrolling till the end of the webpage
4) To scroll Up,Down , Left and Right from current Location :
Left
Right
Up
JavascriptExecutor js = (JavascriptExecutor) driver; js.executeScript(Window.ScrollBy(-2000,0)");
JavascriptExecutor js = (JavascriptExecutor) driver; js.executeScript(Window.ScrollBy(2000,0)");
Up
JavascriptExecutor js = (JavascriptExecutor) driver; js.executeScript(Window.ScrollBy(0,2000)");
Down
JavascriptExecutor js = (JavascriptExecutor) driver; js.executeScript(Window.ScrollBy(0,-2000)");
No comments:
Post a Comment