Thursday, 5 March 2015

Scrolling web page with Webdriver using java

We can scroll the web page using javaScript Executor or You can use the "org.openqa.selenium.interactions.Actions" class to move to an element:

Following classes you required in you java code
import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement;
import org.openqa.selenium.Alert; import org.openqa.selenium.By; import org.openqa.selenium.JavascriptExecutor;

1. We may require to scroll to bottom of the page and then perform operations. For this scenario we can use following code
((JavascriptExecutor) driver).executeScript("window.scrollTo(0, document.body.scrollHeight)");

2. Some times, we may require to scroll to particular element and peform operations on that particular element. For this we need to pass the element on which we need to perform operation. For this scenario we ca use following code
WebElement element = driver.findElement(By.linkText("googleMap")); ((JavascriptExecutor) driver).executeScript("arguments[0].scrollIntoView();", element);
WebElement element = driver.findElement(By.id("my-id"));
Actions actions = new Actions(driver);

3. We can also use the coordinates to scroll to particular position by passing the coordinates. For this scenario we use following code
((JavascriptExecutor) driver).executeScript("window.scrollBy(0,500)");

No comments:

Post a Comment

Which one is right ?