Sometimes, you are required to perform a test action on an element that is not present in the viewable area of a webpage. What do you do in such a situation? With Selenium, you cannot perform a scrolling action directly. However, this can be achieved with two methods:
- Use of JavaScript Executor
- Use of actions class to control the HTML DOM element
Method 1: Use of JavaScript Executor
Selenium can execute commands in JavaScript with the help of the execute_script() method. For the JavaScript solution, we have to pass true value to the method scrollIntoView() to identify the object below our current location on the page.
Code Implementation with Javascript Executor can be found below:
import org.openqa.selenium.By; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; import org.openqa.selenium.chrome.ChromeDriver; import java.util.concurrent.TimeUnit; import org.openqa.selenium.JavascriptExecutor; public class ScrollToViewJs{ public static void main(String[] args) { System.setProperty("webdriver.chrome.driver", "C:\\Users\\ghs6kor\\Desktop\\Java\\chromedriver.exe"); WebDriver driver = new ChromeDriver(); String url = " https://www-stage.testup.io/documentation/"; driver.get(url); driver.manage().timeouts().implicitlyWait(12, TimeUnit.SECONDS); // identify element WebElement l=driver.findElement(By.xpath("//*[text()='Book Onboarding Session']")); // Javascript executor ((JavascriptExecutor)driver).executeScript("arguments[0].scrollIntoView(true);", l); Thread.sleep(800); driver.quit(); } }
Method 2: Use of actions class to control the HTML DOM element
While working with the Actions class to scroll to view, we have to use the moveToElement() method. This method shall perform mouse movement till the middle of the element.
Code implementation with Action class can be found below:
import org.openqa.selenium.By; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; import org.openqa.selenium.chrome.ChromeDriver; import java.util.concurrent.TimeUnit; import org.openqa.selenium.interactions.Action; import org.openqa.selenium.interactions.Actions; public class ScrollToViewActions{ public static void main(String[] args) { System.setProperty("webdriver.chrome.driver", "C:\\Users\\ghs6kor\\Desktop\\Java\\chromedriver.exe"); WebDriver driver = new ChromeDriver(); String url = " https://www-stage.testup.io/documentation/; driver.get(url); driver.manage().timeouts().implicitlyWait(12, TimeUnit.SECONDS); // identify element WebElement l=driver.findElement(By.xpath("//*[text()='Book Onboarding Session']")); // Actions class with moveToElement() Actions a = new Actions(driver); a.moveToElement(l); a.perform(); driver.quit(); } }