1import org.openqa.selenium.JavascriptExecutor;
2import org.openqa.selenium.WebDriver;
3import org.openqa.selenium.chrome.ChromeDriver;
4import org.testng.annotations.Test;
5
6public class ScrollByPixel {
7
8 WebDriver driver;
9 @Test
10 public void ByPixel() {
11 System.setProperty("webdriver.chrome.driver", "E://Selenium//Selenium_Jars//chromedriver.exe");
12 driver = new ChromeDriver();
13
14 JavascriptExecutor js = (JavascriptExecutor) driver;
15
16 // Launch the application
17 driver.get("http://demo.guru99.com/test/guru99home/");
18
19 //To maximize the window. This code may not work with Selenium 3 jars. If script fails you can remove the line below
20 driver.manage().window().maximize();
21
22 // This will scroll down the page by 1000 pixel vertical
23 js.executeScript("window.scrollBy(0,1000)");
24 }
25}
26
1 Selenium does not have a method for scrolling
2 but there are some ways to scroll:
3
4 #1 ->=moveToElement= coming from Actions class
5 will scroll down and up to given web element
6 #2 Using JSExecutor: We can inject JavaScript
7 code in our Java+Selenium code using JSExecutor
8 which helps us scroll up, down, left, right.
9 We need to create instance of JS executor,
10 then cast our driver type of it.
11==================================================
12
13 syntax is =
14 JavaScriptExecutor js = (JavaScriptExecutor) Driver.getDriver();
15 js.executeScript("in here we need to pass js code that scrolls");
16
17
18 js.executeScript("window.scrollBy(0,250)");
19 js.executeScript("arguments[0].scrollIntoView(true);", WebElement);
1Selenium does not have a method for scrolling
2but there are some ways to scroll:
3#1 ->=moveToElement= coming from Actions class
4 will scroll down and up to given web element
5#2 Using JSExecutor: We can inject JavaScript
6 code in our Java+Selenium code using JSExecutor
7 which helps us scroll up, down, left, right.
8 We need to create instance of JS executor,
9 then cast our driver type of it.
10WebDriver driver = new ChromeDriver();
11JavascriptExecutor jse = (JavascriptExecutor)driver;
12jse.executeScript("scroll(0, 250);"); Scroll Down
13jse.executeScript("scroll(0,-250);"); Scroll Up
14