How to scroll up/down a page using Actions class…
We can perform scroll up/down a page using Actions class in Selenium webdriver. First of all, we have to create an object of this Actions class and then apply the sendKeys method on it.
Now, to scroll down a page, we have to pass the parameter Keys.PAGE_DOWN to this method. To again scroll up a page, we have to pass the parameter Keys.PAGE_UP to the sendKeys method. Finally, we have to use the build and perform methods to actually perform this action.
Syntax
Actions a = new Actions(driver); //scroll down a page a.sendKeys(Keys.PAGE_DOWN).build().perform(); //scroll up a page a.sendKeys(Keys.PAGE_UP).build().perform();
package RK1.Building_a_selenium_project;
import java.util.concurrent.TimeUnit;
import org.openqa.selenium.By;
import org.openqa.selenium.Keys;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.interactions.Actions;
public class ScrollUpDownAction {
public static void main(String[] args) {
// TODO Auto-generated method stub
System.setProperty("webdriver.chrome.driver", "F:\\Work Environment\\MyProject\\chromedriver.exe");
WebDriver wd = new ChromeDriver();
String url = "https://www.tutorialspoint.com/index.htm";
wd.get(url);
wd.manage().window().maximize();
wd.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS);
// object of Actions class to scroll up and down
Actions at = new Actions(wd);
at.sendKeys(Keys.PAGE_DOWN).build().perform();
//identify element on scroll down
WebElement l = wd.findElement(By.linkText("Careers"));
String strn = l.getText();
System.out.println("Text obtained by scrolling down is :"+strn);
at.sendKeys(Keys.PAGE_UP).build().perform();
//identify element on scroll up
WebElement m = wd.findElement(By.tagName("h1"));
String s = m.getText();
System.out.println("Text obtained by scrolling up is :"+s);
wd.quit();
}
}