Feeling too lazy to scroll down the web pages. Is there any way to do this in Selenium?
Of course, there is a way. We can do anything almost everything that we do manually with the help of Selenium. Now let's learn how to scroll a web page.
To scroll the web page we are going to use javaScript Executor in our program. Javascript Executor will be helping us to achieve our target. In this example we are going to scroll to the bottom of the page and scroll to a particular portion of the web page.
package seleniumBasics;
import org.openqa.selenium.By;
import org.openqa.selenium.JavascriptExecutor;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;
public class ScrollPage {
public static void main(String[] args) throws InterruptedException {
// TODO Auto-generated method stub
System.setProperty("webdriver.gecko.driver", "C:\\Users\\Elcot\\Desktop\\drivers\\gecko\\geckodriver.exe");
WebDriver driver = new FirefoxDriver();
driver.navigate().to("http://www.echoecho.com/htmlforms11.htm");
//the below line executes to the bottom of the page
((JavascriptExecutor) driver).executeScript("window.scrollTo(0, document.body.scrollHeight)");
Thread.sleep(3000);
//scroll to a bring a portion of the page to view
WebElement previousButton = driver.findElement(By.className("boxprevnext"));
((JavascriptExecutor) driver).executeScript("arguments[0].scrollIntoView();", previousButton);
}
}