How to do Page Scroll Using JavascriptExecutor?
package seleniumwebdriverbestpractices;
import java.util.concurrent.TimeUnit;
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;
import org.testng.annotations.Test;
public class ScrollPage {
WebDriver driver;
@Test
public void scrollingPageTest() throws Throwable{
System.setProperty("webdriver.chrome.driver", System.getProperty("user.dir")+"\\drivers\\chromedriver.exe");
driver = new ChromeDriver();
driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);
// driver.get("https://www.spicejet.com/");
driver.get("https://www.w3schools.com/");
driver.manage().window().maximize();
JavascriptExecutor js = (JavascriptExecutor)driver;
// Scroll Down
js.executeScript("window.scrollBy(0,1000)", "");
Thread.sleep(5000);
// Scroll Up
js.executeScript("window.scrollBy(0,-500)", "");
Thread.sleep(5000);
// Scroll to an element
WebElement element = driver.findElement(By.xpath("//div[@id='main']//a[text()='HTML Exercises']"));
js.executeScript("arguments[0].scrollIntoView(true);", element);
Thread.sleep(5000);
// Scroll to the bottom of the page
js.executeScript("window.scrollBy(0,document.body.scrollHeight)","");
Thread.sleep(5000);
driver.quit();
}
}
import java.util.concurrent.TimeUnit;
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;
import org.testng.annotations.Test;
public class ScrollPage {
WebDriver driver;
@Test
public void scrollingPageTest() throws Throwable{
System.setProperty("webdriver.chrome.driver", System.getProperty("user.dir")+"\\drivers\\chromedriver.exe");
driver = new ChromeDriver();
driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);
// driver.get("https://www.spicejet.com/");
driver.get("https://www.w3schools.com/");
driver.manage().window().maximize();
JavascriptExecutor js = (JavascriptExecutor)driver;
// Scroll Down
js.executeScript("window.scrollBy(0,1000)", "");
Thread.sleep(5000);
// Scroll Up
js.executeScript("window.scrollBy(0,-500)", "");
Thread.sleep(5000);
// Scroll to an element
WebElement element = driver.findElement(By.xpath("//div[@id='main']//a[text()='HTML Exercises']"));
js.executeScript("arguments[0].scrollIntoView(true);", element);
Thread.sleep(5000);
// Scroll to the bottom of the page
js.executeScript("window.scrollBy(0,document.body.scrollHeight)","");
Thread.sleep(5000);
driver.quit();
}
}
This is one awesome blog article. Much thanks again selenium online training
ReplyDelete