Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Scrolling using Selenium WebDriver with Java

I am using Selenium WebDriver to automate my browser tests. My browser header is floating and is always present irrespective of the browser scroll.

So when I click on certain elements that are present below the current visible region of the browser, selenium tries to scroll the element into view and click them.

But because of the auto scrolling as such the elements are scrolled behind the floating header and when any action is performed on them, the elements in the page header get clicked.

is there any way to limit the default scroll of the WebDriver?

like image 854
Rogers Jefrey L Avatar asked Feb 25 '12 10:02

Rogers Jefrey L


People also ask

How do you scroll a page in Selenium WebDriver?

Selenium can execute JavaScript commands with the help of the executeScript method. To scroll down vertically in a page we have to use the JavaScript command window. scrollBy. Then pass the pixel values to be traversed along the x and y axis for horizontal and vertical scroll respectively.

How do you scroll down to the bottom of a page in Selenium Java?

Selenium runs the commands in Javascript with the execute_script() method. For scrolling down to the bottom of the page, we have to pass (0, document. body. scrollHeight) as parameters to the method scrollBy().

Why scroll is not working in Selenium?

Selenium cannot directly scroll up or down with its methods. This is done with the Javascript Executor. DOM can interact with the elements with Javascript. Selenium runs the commands in Javascript with the execute_script() method.

How do you automate scrolling?

Middle-clicking on an area of a webpage, in most modern browsers, will turn your cursor into a multidirectional crosshair. When you move the mouse in a direction away from the starting point of that crosshair, the page will begin to automatically scroll.


2 Answers

    Locatable hoverItem = (Locatable) driver.findElement(By.xpath("//li[text()='Reklama w Google']"));
    int y = hoverItem.getCoordinates().getLocationOnScreen().getY();
    ((JavascriptExecutor)driver).executeScript("window.scrollBy(0,"+y+");");
like image 50
TomaszB Avatar answered Oct 21 '22 15:10

TomaszB


If you want to scroll on the firefox window using selenium webdriver, one of the way is to use javaScript in the java code, The javeScript code to scroll down is as follows:

JavascriptExecutor js = (JavascriptExecutor)driver;
                    js.executeScript("window.scrollTo(0,Math.max(document.documentElement.scrollHeight," +
                    "document.body.scrollHeight,document.documentElement.clientHeight));");
like image 39
Ankit Pandey Avatar answered Oct 21 '22 16:10

Ankit Pandey