How to do scrolling in the webpage using Selenium Java

asked 11 months ago

Sometimes the web element might not appear on the webpage's eye view, selenium webdriver interact with the web element which they appear in the webpage. To interact with such elements we need to scroll up, down, horizontal and vertical movement. To do scrolling on the web page, there are a few methods available in the selenium webdriver.

Navigate to https://www.qafeast.com/demo  ,click the Scrolling tab.

scrolling_selenium_Java

The submit button is at the bottom of the page, selenium webdriver mimics a user to click the control. The submit button is not visible to the user, if selenium scripts are written to click the button then it will throw an error "Element not visible".In order to click the submit button, we can make the scroll at the end of the page, and the button will be visible to click. 

To scroll to the webpage JavascriptExecutor class is used.

 

Scroll to the element:

We can scroll to the particular element, the element could be at the bottom or horizontal using the scroll into view method the focus moved to the element.

WebElement element= driver.findElement(By.id("<>"));
((JavascriptExecutor)driver).executeScript("arguments[0].scrollIntoView();", element); 

 

Scroll to the bottom of the page

JavascriptExecutor js = ((JavascriptExecutor) driver);
js.executeScript("window.scrollTo(0, document.body.scrollHeight)");

 

Scroll down to some extent

JavascriptExecutor jse = (JavascriptExecutor)driver;
jse.executeScript("window.scrollTo(0,250)");

 

Scroll to top of the page

JavascriptExecutor js = ((JavascriptExecutor) driver);
js.executeScript("window.scrollTo(document.body.scrollHeight, 0)");

 

Scroll up to some extent

JavascriptExecutor jse = (JavascriptExecutor)driver;
jse.executeScript("scroll(0, -250);");

 

Categories