Write a selenium web driver test script to scroll and print all items name from a web page. Below is an example using FlipKart.
Scenario
- Log in to Flipkart.
- Type Samsung in search box and Click search button.
- Click mobile link.
- Scroll and print all the names.
Scrolling is the only challenging portion here, until when we have to scroll is the question. In the above scenario we will scroll the web page until no-more-results are displayed.
package chubJava; import java.util.List; import org.openqa.selenium.By; import org.openqa.selenium.JavascriptExecutor; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; import org.openqa.selenium.firefox.FirefoxDriver; public class FKart_Test { static WebDriver driver=new FirefoxDriver(); public static void main(String[] args) { driver = new FirefoxDriver(); driver.get("http://www.flipkart.com"); driver.findElement(By.id("fk-top-search-box")).sendKeys("Nokia"); driver.findElement(By.xpath("//form[@id='fk-header-search-form']/div/div/div[2]/input[1]")).click(); driver.findElement(By.partialLinkText("Mobiles")).click(); JavascriptExecutor jse = (JavascriptExecutor) driver; int count = 1500; while (!driver.findElement(By.id("no-more-results")).isDisplayed()) { count = count + 500; jse.executeScript("scroll(0, " + count + ")"); try { Thread.sleep(500); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } if (driver.findElement(By.id("show-more-results")).isDisplayed()) { driver.findElement(By.id("show-more-results")).click(); } } List<WebElement> al = driver.findElements(By.xpath("//div[contains(@class,'pu-title')]/a")); System.out.println(al.size()); for (int i = 0; i < al.size(); i++) { System.out.println(al.get(i).getText()); } driver.close(); } }
Ping us for any help. Like us at Facebook.
No comments:
Post a Comment