Scrolling Web Pages using Selenium WebDriver


There are 3 different ways to Scroll Web Pages.

1.Scroll page by proving pixel number.
2. Scroll page till we find a web element on the page
3. Scroll page till bottom of the page


To scroll web page using Selenium, we can use JavaScriptExecutor interface that helps to execute JavaScript methods through Selenium Webdriver.


Syntax:
window.scrollBy(xnum, ynum)
Parameters:
  • xnum is a Number
  • Required. How many pixels to scroll by, along the x-axis (horizontal). Positive values will scroll to the right, while negative values will scroll to the left
  • ynum is a Number
  • Required. How many pixels to scroll by, along the y-axis (vertical). Positive values will scroll down, while negative values scroll up

Return Value: No return value



Examples:
Scroll page by proving pixel number
  js.executeScript("window.scrollBy(0,500)");

Scroll page till we find a web element on the page
  js.executeScript("arguments[0].scrollIntoView();",Element );

 Scroll page till bottom of the page
  js.executeScript("window.scrollTo(0, document.body.scrollHeight)");

Test Script

import org.openqa.selenium.By;
import org.openqa.selenium.JavascriptExecutor;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;

public class Scrolling {
public static void main(String[] args) {
System.setProperty("webdriver.chrome.driver", "C://Drivers/chromedriver_win32/chromedriver.exe");
WebDriver driver = new ChromeDriver();

driver.get("https://www.countries-ofthe-world.com/flags-of-the-world.html");
driver.manage().window().maximize(); // maximum browser window

JavascriptExecutor js = (JavascriptExecutor) driver;

// 1. scrolling by using pixel
js.executeScript("window.scrollBy(0,1000)", "");

// 2. scrolling page till we find element
WebElement flag = driver
.findElement(By.xpath("//*[@id='content']/div[2]/div[2]/table[1]/tbody/tr[86]/td[1]/img"));
js.executeScript("arguments[0].scrollIntoView();", flag);

// 3. scroll page till bottom
js.executeScript("window.scrollTo(0,document.body.scrollHeight)");
}
}

Followers