There are some situations in which we want to scroll to a particular element or scroll up or down across the browser, and also we can scroll inside a dropdown or list box to get all the available options.
Selenium do not have it’s own methods to perform this action, so we can use javascript to play on scrollbars.
To scroll on a web page –
public class ScrollTest { public static void main(String[] args) throws InterruptedException { WebDriver driver; System.setProperty("webdriver.chrome.driver", "/Users/sunilkumarpatro/sel/chromedriver"); driver = new ChromeDriver(); driver.get("http://qavalidation.com/demo"); JavascriptExecutor js = (JavascriptExecutor) driver; //Scroll page down to 250px js.executeScript("window.scrollBy(0,250)", ""); //or //js.executeScript("scroll(0,250)"); Thread.sleep(3000); //Scroll page to view an element WebElement element = null; element = (WebElement) js.executeScript("return document.getElementById('tools');"); js.executeScript("arguments[0].scrollIntoView(true);",element); Thread.sleep(3000); driver.quit(); } }
Note
These 2 below lines will scroll till the “Automation Tools” list box section on browser screen
element = (WebElement) js.executeScript("return document.getElementById('tools');");
js.executeScript("arguments[0].scrollIntoView(true);",element);
Another way –
Actions action = new Actions(driver); action.sendKeys(Keys.PAGE_DOWN).perform();
To scroll inside a dropdown / list box –
Above ways to scroll on a browser screen, but there are situations in which we need to scroll on a dropdown list, then we need to 1st locate the dropdown list and then perform scrolling
Example – on our demo screen, let’s say we want to scroll inside the Automation tools list box section, then you can use below code
js.executeScript("elem = document.querySelector('#tools'); elem.scrollTop = elem.scrollTop + 100");
document.querySelector() locates the list box and scrolls 100px down, you can change the value with your need.
Complete code block
public class ScrollTest { public static void main(String[] args) throws InterruptedException { WebDriver driver; System.setProperty("webdriver.chrome.driver", "/Users/sunilkumarpatro/sel/chromedriver"); driver = new ChromeDriver(); driver.get("http://qavalidation.com/demo"); JavascriptExecutor js = (JavascriptExecutor) driver; //Scroll page to view an element WebElement element = null; element = (WebElement) js.executeScript("return document.getElementById('tools');"); js.executeScript("arguments[0].scrollIntoView(true);",element); Thread.sleep(3000); //scroll into the list box js.executeScript("elem = document.querySelector('#tools'); elem.scrollTop = elem.scrollTop + 100"); Thread.sleep(4000); driver.quit(); } }
1 Comment