scroll a long web page in selenium webdriver
package SeleniumPractice;
import java.text.ParseException;
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.openqa.selenium.interactions.Actions;
import org.testng.Assert;
import org.testng.annotations.Test;
public class AddCookiesInSelenium {
WebDriver driver;
@Test
public void enterText() {
try {
// First step set the driver location
System.setProperty(“webdriver.chrome.driver”, “C:\\softwares\\Selenium jars\\chromedriver.exe”);
// create chrome object
driver = new ChromeDriver();
driver.get(“https://www.tirerack.com/content/tirerack/desktop/en/homepage.html”);
// it will go till the end vertically
((JavascriptExecutor) driver).executeScript(“window.scrollTo(0, document.body.scrollHeight)”);
// it will come up vertically
((JavascriptExecutor) driver).executeScript(“window.scrollTo(0, -document.body.scrollHeight)”);
Thread.sleep(3000);
// it will go till the pixel specified
((JavascriptExecutor) driver).executeScript(“window.scrollBy(0,1500)”);
Thread.sleep(3000);
// it will come back till the pixel specified
((JavascriptExecutor) driver).executeScript(“window.scrollBy(0,-1500)”);
Thread.sleep(3000);
// it will go down till the object specified.
((JavascriptExecutor) driver).executeScript(“arguments[0].scrollIntoView(true);”,
driver.findElement(By.xpath(“//a[contains(text(),’Find’)]”)));
}catch(Exception e) {
System.out.println(“Exception details”+e.getMessage());
}
driver.quit();
}
}
Another method to scroll a WebDriver instance (via JavascriptExecutor):
WebDriver driver;
driver = new FirefoxDriver();
driver.get(“https://www.urlwithlongPages.xxx”);
Boolean readyStateComplete = false;
while (!readyStateComplete) {
JavascriptExecutor executor = (JavascriptExecutor) driver;
executor.executeScript(“window.scrollTo(0, document.body.offsetHeight)”);
readyStateComplete = (String) executor.executeScript(“return document.readyState”) == “complete”;
}
0 comments